简体   繁体   English

饼干不工作的记得我在asp.net

[英]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: 并在web.config和以下代码中使用machinekey:

<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. 我在浏览器中检查cookie,.ASPXAUTH已保存,并且日期过期是可以的。 but after a few minutes, asp.net not use cookies is browser and remember me not working! 但是几分钟后,asp.net不能使用cookie的浏览器,记住我无法正常工作!

You also want to set cookie expiration same as ticket expiration. 您还希望将cookie到期时间设置为与票证到期时间相同。

...
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 . FYI:您可能想要删除timeout="20"cookieless="UseCookies"这是默认值

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

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