9

I'm using ASP.NET forms authentication for logging users into a website we're developing.

Part of the functionality is a "Remember me" checkbox which remembers the user for a month if they check it.

The code for logging the user in is as follows:

public static void Login(HttpResponse response, string username,
  bool rememberMeChecked)
{
  FormsAuthentication.Initialize();
  FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username, DateTime.Now,
    DateTime.Now.AddMinutes(30), rememberMeChecked,
    FormsAuthentication.FormsCookiePath);
  HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tkt));
  ck.Path = FormsAuthentication.FormsCookiePath;

  if (rememberMe)
    ck.Expires = DateTime.Now.AddMonths(1);

  response.Cookies.Add(ck);
}

The relevant section in the web.config is this:

<authentication mode="Forms">
  <forms loginUrl="Home.aspx" defaultUrl="~/" slidingExpiration="true" timeout="43200" />
</authentication>

This logs the user fine but logs them out after half an hour if they don't use the site, although its persistence property (rememberMeChecked) is set to true and if it is true, the cookie is set to expire after a month. Is there something I'm missing here?

Thanks in advance, F

4

5 回答 5

7

看起来您的身份验证票证仍配置为半小时后过期,即使 cookie 本身在 30 天后过期。您可能还必须延长票证的使用寿命:

public static void Login(HttpResponse response, string username,
    bool rememberMeChecked)
{
    DateTime expiration = DateTime.Now.AddMinutes(30);
    if (rememberMe) {
        expiration = DateTime.Now.AddMonths(1);
    }

    FormsAuthentication.Initialize();
    FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username,
        DateTime.Now, expiration, rememberMeChecked,
        FormsAuthentication.FormsCookiePath);

    HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName,
        FormsAuthentication.Encrypt(tkt));
    ck.Path = FormsAuthentication.FormsCookiePath;
    response.Cookies.Add(ck);
}
于 2011-01-31T13:25:30.467 回答
1

尝试在 web.config 中设置 forms 标签的Name属性

此外,Firecookie在调试这类问题方面也很棒

只需再次阅读您的代码,您还可以DateTime.Now.AddMinutes(30)在票证构造函数中指定...必须检查这是否会影响它

于 2011-01-31T13:21:15.897 回答
0

It looks to me that you're checking "rememberMe" rather than the variable you passed called "rememberMeChecked".

于 2011-01-31T13:21:15.460 回答
0

您已DateTime.Now.AddMinutes(30)在构造函数中指定FormsAuthenticationTicket. 这就是设置登录的过期时间。

于 2011-01-31T13:22:47.020 回答
0

我意识到必须更新身份验证票,而不仅仅是阅读。我的 Application_BeginRequest 方法现在看起来像这样:

 if (!Request.IsAuthenticated)
  {
    HttpCookie ck = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (ck != null)
    {
      FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(ck.Value);
      UserManagementUtils.RenewFormsAuthenticationTicket(Response, oldTicket);
    }
  }

这似乎已经解决了它。

于 2011-01-31T15:07:40.450 回答