【发布时间】:2010-07-03 03:26:13
【问题描述】:
我在 ASP.NET 应用程序中使用表单身份验证。我将FormsAuthenticationTicket 配置为在 1 年内到期,但它实际上在 1 小时左右后到期。我不知道为什么。
以下是登录过程中涉及的所有代码:
public static bool Login(int id)
{
try
{
string securityToken = UserHelper.AuthenticateUser(id);
DateTime expiryDate = DateTime.Now.AddYears(1);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, id.ToString(), DateTime.Now, expiryDate, true,
securityToken, FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.Expires = expiryDate;
HttpContext.Current.Response.Cookies.Add(cookie);
return true;
}
catch
{
return false;
}
}
Web.config:
<system.web>
<machineKey validationKey="AutoGenerate"
decryptionKey="AutoGenerate" validation="SHA1" />
<compilation debug="true">
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" timeout="2880"/>
</authentication>
...
我的方法有问题吗?为什么过期这么快?
编辑
Global.asax 代码:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.PhysicalPath.EndsWith(".aspx") || Request.PhysicalPath.EndsWith(".axd") || Request.PhysicalPath.EndsWith(".ashx"))
SecurityManager.SetPrincipal();
}
设置主体代码:
public static void SetPrincipal()
{
ILivrePrincipal principal = null;
FormsIdentity identity;
UrlParameters urlParameters = UrlParametersHelper.GetUrlParameters(HttpContext.Current.Request);
if (HttpContext.Current.Request.IsAuthenticated)
{
identity = (FormsIdentity)HttpContext.Current.User.Identity;
User userProfile;
urlParameters.SecurityToken = (((FormsIdentity)identity).Ticket).UserData;
try
{
userProfile = UserHelper.GetUser(urlParameters.SecurityToken);
UserHelper.UpdateLastActiveOn(userProfile);
principal = new AuthenticatedPrincipal(identity, userProfile);
}
catch
{
//TODO: Log an exception
FormsAuthentication.SignOut();
principal = new AnonymousPrincipal(new GuestIdentity(), UserHelper.GetUser(null));
}
}
else
{
principal = new AnonymousPrincipal(new GuestIdentity(), UserHelper.GetUser(null));
}
HttpContext.Current.User = principal;
}
【问题讨论】:
-
为什么你有
timeout="2880"(指定2天)? -
@Gabe 谢谢。我同意你。这是一个错误,但仍然无法解释为什么我的登录会话会在大约一个小时后到期。
标签: c# .net asp.net authentication forms-authentication