为什么我的ASP.NET MVC持久身份验证cookie不起作用?

Mat*_*rts 16 asp.net cookies asp.net-mvc forms-authentication

我正在使用ASP.NET MVC 3,使用表单身份验证(基于使用file-> new获得的修改后的vanilla帐户代码).

当您登录时,我正在设置一个身份验证cookie

FormsAuthentication.SetAuthCookie(userName, true);
Run Code Online (Sandbox Code Playgroud)

所以这应该设置一个持久的cookie.但是,如果我关闭浏览器并重新打开,当我浏览到该网站时,我被迫再次登录!我可以看到使用chrome dev工具创建cookie(.ASPXAUTH)并在关闭浏览器时不被删除,所以发生了什么?

我的web.config:

<authentication mode="Forms">
  <forms loginUrl="~/Account/LogIn" timeout="10000"/>
</authentication>
Run Code Online (Sandbox Code Playgroud)

我正在IIS下本地测试这个,如果这有任何区别的话.

Tom*_*uλa 8

我最好用身份验证票创建一个cookie. SetAuthCookie在引擎盖下创建一个身份验证票.你有没有尝试制作自己的身份证?它可以让你存储额外的数据.

这是一个例子:

// create encryption cookie         
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, 
        userName, 
        DateTime.Now,
        DateTime.Now.AddDays(90),
        createPersistentCookie, 
        string.Empty);

// add cookie to response stream         
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);    
System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
if (authTicket.IsPersistent) 
{     
      authCookie.Expires = authTicket.Expiration; 
}
System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);  
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.


Mat*_*rts 4

根据@alexl 的评论解决:

\n\n

你可以检查这个答案:Making user Login persisted with ASP .Net Membership

\n\n

好的,这个链接似乎为我排序了 - 坚持使用 SetAuthCookie 并调整我的配置以显式设置 cookie 名称(在 web.confg 中),现在一切正常。诡异的!\xe2\x80\x93

\n