[英]MVC4 Forms Authentication Auto Login
因此,我要完成的工作是为我的应用程序用户提供一个基本的“记住我”样式的操作。
到目前为止,我已经完成了所有内容的编写,并且大多数时候都可以按预期进行。 不过,有时候,检查持久性Forms Authentication票证的方法不会自动登录,而且我不知道为什么它只是偶尔发生。
要测试我的代码,我要做的是启动调试器,在chrome的dev工具中手动杀死我的会话cookie,然后重新加载页面。 逐步执行代码,它按预期进入自动登录方法,然后继续重置我的会话数据。 但是,如果我等待的时间过长(例如大约4个小时),然后尝试相同的操作,它不会自动重置会话。 (假设我已经让调试器运行了一段时间。)
编辑 :为清楚起见,当发生此错误时,我可以打开开发工具并查看身份验证票证仍然可用。 只是用于重置我的会话的代码未在运行,原因是某个地方出错了。 由于这种情况发生的频率不高,因此很难追踪。
所以,到代码上。
我在控制器的构造函数中调用静态void自动登录方法,并将httpcontext传递到自动登录方法中。
控制者
public class SiteController : Controller
{
public SiteController()
{
this.UserAutoLogin(System.Web.HttpContext.Current);
}
// GET: /Site/
public ActionResult Index()
{
ViewBag.CatNav = this.RenderNavCategories();
return View();
}
}
自动登录代码
public static void UserAutoLogin(this Controller Controller, System.Web.HttpContext context)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
if (ticket != null)
{
if (ticket.Name.Length > 0)
{
try
{
if (context.Session["UserName"] == null)
{
//get user from db
PersonRepository PersonRepo = new PersonRepository();
PersonModel Member = PersonRepo.GetUserUserName(ticket.Name);
if (Member.FirstName != null) //if this is null...then the cookie is wrong, so don't do shit
{
//Set the session parameters
context.Session["FirstName"] = Member.FirstName;
context.Session["LastName"] = Member.LastName;
context.Session["UserId"] = Member.Id;
context.Session["UserName"] = Member.Username;
context.Session["Email"] = Member.Email;
context.Session["IsUser"] = 1;
context.Session["Zip"] = Member.Zip;
FormsAuthentication.SignOut();
FormsAuthentication.SetAuthCookie(Member.Username, true);
}
}
}
catch (Exception ex)
{
// don't do anything for now - do something smart later :)
Console.WriteLine(ex.ToString());
}
}
}
}
}
因为当IIS回收应用程序时,会生成一个新的机器密钥。 FormsAuthentication票证是使用该密钥签名的,因此当密钥更改时,旧票证将无法识别。 您需要使用固定的机器钥匙。
编辑 :删除了到密钥生成器站点的链接(现已终止)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.