Auth cookie不是持久的

时间:2015-02-14 11:44:51

标签: asp.net-mvc cookies forms-authentication

我有以下代码,并根据其他stackoverflow答案,它应该工作,但它没有。我错过了别的什么吗?

DateTime expiration = DateTime.Now.AddMinutes(30);
if (rememberMe)
{
    expiration = DateTime.Now.AddMonths(1);
}
HttpContext.Current.Response.Cookies.Clear();

var ticket = new FormsAuthenticationTicket(1, email, DateTime.Now, expiration, rememberMe,
guid.ToString(), FormsAuthentication.FormsCookiePath);

string encryptedTicket = FormsAuthentication.Encrypt(ticket);

var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.Expires = ticket.Expiration;
HttpContext.Current.Response.Cookies.Add(cookie);

并在Application_AuthenticateRequest

中阅读Cookie
var authCookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (authCookie == null) return;

var ticket = FormsAuthentication.Decrypt(authCookie.Value);
if (ticket == null) return;
...

和我的web.config条目:

<authentication mode="Forms">
     <forms loginUrl="~/Home/Index" timeout="30" /> <!--  30minutes
</authentication>

1 个答案:

答案 0 :(得分:0)

1 - 在asp.net项目的root web.config中,在system.web部分中,将身份验证模式设置为“Forms”:

<system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <authentication mode="Forms">
      <forms loginUrl="login" timeout="18000" />
    </authentication>
</system.web>

2 - 对于持久身份验证密钥使用:

using System.Web.Security;

FormsAuthentication.SetAuthCookie(userName,false);

3-对于读取当前验证密钥,请使用:

var userName=controller.User.Identity.Name;