如何使用表单身份验证提供保持登录功能?

时间:2012-08-06 19:18:58

标签: asp.net-mvc forms-authentication

我正在生成一个FormsAuthentication票证,并将其存储在cookie中,我将其与MVC AuthorizeAttribute一起使用以提供授权。现在,我已经知道,如果我有一个"保持登录状态,那么cookie就不会过期。选中复选框,(我只是将cookie更改为现在+ 1年,用于测试目的,当他们检查并保持登录时)。

但是,即使我在创建故障单时设置cookie是持久的,但在超时期限后故障单仍然停止工作。

这是我创建AuthTicket的代码:

var now = DateTime.UtcNow.ToLocalTime();
FormsAuthenticationTicket authTicket = new System.Web.Security.FormsAuthenticationTicket(1, username, now, now.Add(FormsAuthentication.Timeout), rememberMe, username, FormsAuthentication.FormsCookiePath);
string encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket);
return encryptedTicket;

这是我设置为cookie的相同encryptedTicket。任何人都知道如何让这张票允许超过FormsAuthentication超时?我是否只需要手动处理FormsAuthentication超时时间?

1 个答案:

答案 0 :(得分:4)

Cookie粘贴的时间与登录保持有效的时间不同。基本上,持久性cookie是“如果此cookie在浏览器关闭后仍然存在”,并且与此登录有效期无关。您可以使用它来存储用户名,以便用户在返回时不必重新输入此信息。

如果cookie有效,但登录已在cookie中过期,则需要再次登录。如果您希望登录时间更长,则需要在web.config中的<forms>标记上延长时间,或者您可以在代码中执行此操作,但如果要延长/缩短,则需要重新编译到期时间。

以下是一些可以进一步解释这些概念的网站:

http://software-security.sans.org/blog/2012/04/05/forms-authentication-remember-me-its-hard-not-too

Cookie Confusion with FormsAuthentication.SetAuthCookie() Method