Sam*_*Sam 3 c# asp.net asp.net-mvc forms-authentication
我正在使用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);
Run Code Online (Sandbox Code Playgroud)
这会创建一个加密的票证并将其发送到浏览器.我已经使用开发人员工具和Fiddler验证了该票证是否存在于浏览器中,并且在后续请求中将其发送回服务器.
但身份验证现在已被破坏.此外,cookie不可用于Application_AuthenticateRequest或Application_PostAuthenticateRequest事件中.当我使用调试器进行探索时,Context.Request.Cookies它不在列表中.
奇怪的是,如果我退回管道并检查它,cookie确实存在Application_BeginRequest:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以看起来有些事情是在BeginRequest之前但以前从我的自定义FormsAuthenticationTicket中剥离出来的AuthenticateRequest.不幸的是,这会破坏网站上的身份验证.
创建自定义故障单时,是什么原因导致了这种行为?我的cookie创建有问题吗?
| 归档时间: |
|
| 查看次数: |
6425 次 |
| 最近记录: |