Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

c# - Remember me functionality in ASP.NET Form Authentication doesn't work

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like your authentication ticket is still configured to expire after half an hour, even if the cookie itself expires in 30 days. You probably have to extend the ticket's lifetime too:

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...