【发布时间】:2018-10-11 07:41:03
【问题描述】:
我遇到了一个问题,即 ASP.Net Web 应用程序的 cookie 过期太快。
我已将 cookie 设置为 3 小时后过期,并且未在 webconfig 中设置超时,但用户在 1 小时后被定向到登录屏幕。
如果我将 cookie 过期时间设置为 1 分钟,它会在 1 分钟后将用户注销,所以我猜一小时后会有其他东西覆盖它,但我不确定在哪里查看。
我的表单身份验证和会话状态 web 配置条目,以及用于创建 cookie 和查找 cookie 的代码可以在下面看到。
<sessionState mode="InProc" timeout="525600" />
<authentication mode="Forms">
<forms loginUrl="~/Login.aspx" name=".VRBAdmin" enableCrossAppRedirects="false" cookieless="UseCookies" />
</authentication>
<authorization>
protected void OnLogin(object sender, EventArgs e)
{
if (Membership.ValidateUser(this.uxUser.Text, this.uxPassword.Text))
{
string userData = string.Join("|", Roles.GetRolesForUser(this.uxUser.Text));
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
this.uxUser.Text, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddHours(3), // expiryDate
true, // true to persist across browser sessions
userData, // can be used to store additional user data
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
// Add the cookie to the request to save it
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
// Your redirect logic
Response.Redirect(FormsAuthentication.GetRedirectUrl(this.uxUser.Text, true));
}
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
//Extract the forms authentication cookie
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
// If caching roles in userData field then extract
string[] roles = authTicket.UserData.Split(new char[] { '|' });
// Create the IIdentity instance
IIdentity id = new FormsIdentity(authTicket);
// Create the IPrinciple instance
IPrincipal principal = new GenericPrincipal(id, roles);
// Set the context user
Context.User = principal;
}
}
【问题讨论】:
-
你在用
ASP.NET Membership Provider吗? -
是的,我正在使用会员服务提供商
标签: asp.net authentication cookies forms-authentication