ASP.NET MVC RememberMe

前端 未结 5 1995
花落未央
花落未央 2020-12-07 15:33

After searching a lot i did not get any answers and finally i had to get back to you. Below i am explaining my problem in detail. It\'s too long, so please don\'t quit readi

5条回答
  •  孤街浪徒
    2020-12-07 15:50

    What you want to do is have a different timeout when the RememberMe option is checked, than when it is unchecked. Unfortunately, the SetAuthCookie method does not allow you to set the expiration manually, so you'll have to do that yourself.

    The problem is then, how to do that?

    ASP.NET MVC uses the FormsAuthentication class of System.Web.Security to do that, because it's not trivial if you also want to support the configuration settings and cookieless browsing and SSL, but I think that if you simply do this:

    int timeout = rememberMe ? 525600 : 30; // Timeout in minutes, 525600 = 365 days.
    var ticket = new FormsAuthenticationTicket(userName, rememberMe, timeout);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);// Not my line
    cookie.HttpOnly = true; // cookie not available in javascript.
    Response.Cookies.Add(cookie);
    

    ...you'll get a basic version of what you need.

    NOTE: I did not test this code.

提交回复
热议问题