简体   繁体   English

MVC4表单身份验证自动登录

[英]MVC4 Forms Authentication Auto Login

So, what I am trying to accomplish is a basic "remember me" style action for users of my application. 因此,我要完成的工作是为我的应用程序用户提供一个基本的“记住我”样式的操作。

I have completed writing everything so far, and it is working as expected most of the time. 到目前为止,我已经完成了所有内容的编写,并且大多数时候都可以按预期进行。 Occasionally though, the method to check for the persistent Forms Authentication ticket doesn't auto login, and I can't figure out why it is only happening occasionally . 不过,有时候,检查持久性Forms Authentication票证的方法不会自动登录,而且我不知道为什么它只是偶尔发生。

To test my code, what I have done is start the debugger, manually kill my session cookie in chrome's dev tools, then reload the page. 要测试我的代码,我要做的是启动调试器,在chrome的dev工具中手动杀死我的会话cookie,然后重新加载页面。 Stepping through the code, it enters into the auto login method as expected and proceeds to reset my session data. 逐步执行代码,它按预期进入自动登录方法,然后继续重置我的会话数据。 However, if I wait an inordinate amount of time, like 4 hours perhaps, and try the same thing it does not auto reset my session. 但是,如果我等待的时间过长(例如大约4个小时),然后尝试相同的操作,它不会自动重置会话。 (Assuming that i've left the debugger running for that amount of time). (假设我已经让调试器运行了一段时间。)

EDIT : For clarity's sake, when this error is happening, I can open the dev tools and see that the authentication ticket is still available. 编辑 :为清楚起见,当发生此错误时,我可以打开开发工具并查看身份验证票证仍然可用。 It's just the code to reset my session is either not running, for erroring out somewhere. 只是用于重置我的会话的代码未在运行,原因是某个地方出错了。 Due to the infrequency in which this is happening, it's hard to track down. 由于这种情况发生的频率不高,因此很难追踪。

So, onto the code. 所以,到代码上。

I'm calling the static void auto login method in the controller's constructor, and passing the httpcontext into the auto login method. 我在控制器的构造函数中调用静态void自动登录方法,并将httpcontext传递到自动登录方法中。

Controller 控制者

public class SiteController : Controller
{
    public SiteController()
    {
       this.UserAutoLogin(System.Web.HttpContext.Current);
    }

    // GET: /Site/
    public ActionResult Index()
    {
        ViewBag.CatNav = this.RenderNavCategories();
        return View();
    }
}

Auto Login Code 自动登录代码

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());
                }
            }
        }
    }
}

Because when IIS is recycling the app, a new machine key is generated. 因为当IIS回收应用程序时,会生成一个新的机器密钥。 The FormsAuthentication ticket is signed using that key so when the key changes the old ticket isn't recognized. FormsAuthentication票证是使用该密钥签名的,因此当密钥更改时,旧票证将无法识别。 You need to use a fixed machine key. 您需要使用固定的机器钥匙。

Edit : Removed link to key generator site (now defunct) 编辑 :删除了到密钥生成器站点的链接(现已终止)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM