我在 Logon 方法中设置 FormsAuthenticationTicket 以手动创建身份验证 cookie。如何验证该身份验证 cookie 并将其分配给 Current.User 对象。它是在 Global.asax 页面中完成的吗?
登录代码:
FormsAuthenticationTicket Authticket = new
FormsAuthenticationTicket(1,
model.UserName,
DateTime.Now,
DateTime.Now.AddYears(1),
true,
"",
FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(Authticket);
HttpCookie Authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (Authticket.IsPersistent) Authcookie.Expires = Authticket.Expiration;
Response.Cookies.Add(Authcookie);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
我如何读取此 cookie 并验证用户?
到目前为止我在 global.asax 文件中的代码:
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
FormsIdentity id = new FormsIdentity(authTicket);
GenericPrincipal principal = new GenericPrincipal(id,null);
Context.User = principal;
}
最佳答案
我将这种类型的代码移到了基本 Controller 中。 Controller 类中有一个名为“OnAuthorization”的方法可以被覆盖。
已经有一段时间了,但我相信所有请求(图像、css 等)都通过 Global.asax 中的 OnAuthorization 方法。通过将授权推送给 Controller ,您只会收到对 Controller /操作的请求
关于asp.net-mvc - Asp.Net MVC FormsAuthenticationTicket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3260766/