gpt4 book ai didi

c# - 缺少 ASP.net MVC FormsAuthentication cookie

转载 作者:行者123 更新时间:2023-11-30 14:30:08 25 4
gpt4 key购买 nike

我正在使用 FormsAuthentication 编写 ASP.net MVC 5 应用程序。我使用 FormsAuthentication.SetAuthCookie(user.Email, model.RememberMe) 准备好一切并正常工作。

但是,我想创建一个自定义票证,这样我就可以在票证的 UserData 字段中存储一些额外的信息。这就是我创建票证并将其存储在 cookie 中的方式:

var ticket = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.Minutes), model.RememberMe, user.AuthToken);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Domain = FormsAuthentication.CookieDomain, Path = FormsAuthentication.FormsCookiePath, HttpOnly = true, Secure = FormsAuthentication.RequireSSL };
HttpContext.Response.Cookies.Add(cookie);

这会创建一个加密的票证并将其发送到浏览器。我已经使用开发人员工具和 Fiddler 验证了该票证存在于浏览器中,并且在后续请求中将其发送回服务器。

但是身份验证现在被破坏了。此外,cookie 在 Application_AuthenticateRequestApplication_PostAuthenticateRequest 事件中不可用。当我使用调试器探索 Context.Request.Cookies 时,它不在列表中。

奇怪的是,如果我返回管道并在 Application_BeginRequest 中检查它,cookie 确实存在:

void Application_BeginRequest(object sender, EventArgs e)
{
// Auth cookie exists in the collection here! Ticket decrypts successfully
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;
var encTicket = authCookie.Value;
var ticket = FormsAuthentication.Decrypt(encTicket);
}

void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Auth cookie missing from the cookies collection here!
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie == null)
return;

var encTicket = authCookie.Value;
var ticket = FormsAuthentication.Decrypt(encTicket);
using (var db = new BadgerContext())
{
var user = db.Users.OfType<RegisteredUser>().FirstOrDefault(x => x.UserName == ticket.Name);
if (ticket.UserData != user.AuthToken)
{
FormsAuthentication.SignOut();
Response.Redirect(FormsAuthentication.DefaultUrl);
}
}
}

看来在 BeginRequest 之后但在 AuthenticateRequest 之前,某些东西正在从 cookie 中剥离我的自定义 FormsAuthenticationTicket。不幸的是,这完全破坏了网站上的身份验证。

创建自定义票证时,知道是什么导致了这种行为吗?我的 cookie 创建有问题吗?

最佳答案

检查 system.web 中的 .config 文件节点,httpRuntime标签。

<httpRuntime targetFramework="4.5" />

与主网站相同

关于c# - 缺少 ASP.net MVC FormsAuthentication cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24197556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com