简体   繁体   中英

cookie not working for remember me in asp.net

I use this code for login in website:

var userId = User.UserId;
var userData = userId.ToString(CultureInfo.InvariantCulture);
var authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(30), persistanceFlag, userData, FormsAuthentication.FormsCookiePath);
var encTicket = FormsAuthentication.Encrypt(authTicket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
if (authTicket.IsPersistent)
     {
          cookie.Expires = DateTime.Now.AddMonths(6);
     }

and use machinekey in web.config and this code:

<sessionState mode="InProc" timeout="20" cookieless="UseCookies" />
<httpCookies httpOnlyCookies="true" />
<authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" timeout="2880" cookieless="UseCookies" />
</authentication>

but remember me is not working! I check cookie in browser, .ASPXAUTH is saved and date expires is ok. but after a few minutes, asp.net not use cookies is browser and remember me not working!

You also want to set cookie expiration same as ticket expiration.

...
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                HttpOnly = true,
                Secure = FormsAuthentication.RequireSSL,
                Path = FormsAuthentication.FormsCookiePath
            };
if (authTicket.IsPersistent)
{
   cookie.Expires = encTicket.Expiration;
}
if (FormsAuthentication.CookieDomain != null)
{
   cookie.Domain = FormsAuthentication.CookieDomain;
}
Response.Cookies.Add(cookie);

FYI: You might want to remove timeout="20" and cookieless="UseCookies" which are default values .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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