当用户登录我的网站时,我会创建以下身份验证票证:
// Create the authentication ticket
var authTicket = new FormsAuthenticationTicket(1, // Version
userName, // Username
DateTime.UtcNow, // Creation
DateTime.UtcNow.AddMinutes(10080), // Expiration
createPersistentCookie, // Persistent
user.Role.RoleName + "|~|" + user.UserID + "|~|" + user.TimeZoneID); // Additional data
// Encrypt the ticket
var encTicket = FormsAuthentication.Encrypt(authTicket);
// Store the ticket in a cookie
HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = authTicket.Expiration });
然后在我的Global.asax.cs文件中,我有以下内容:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Get the authentication cookie
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
// If it exists then decrypt and setup the generic principal
if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value))
{
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
var id = new UserIdentity(ticket); // This class simply takes the value from the cookie and then sets the properties on the class for the role, user id and time zone id
var principal = new GenericPrincipal(id, new string[] { id.RoleName });
HttpContext.Current.User = principal;
}
}
protected void Session_Start(object sender, EventArgs e)
{
// If the user has been disabled then log them out
if (Request.IsAuthenticated)
{
var user = _userRepository.Single(u => u.UserName == HttpContext.Current.User.Identity.Name);
if (!user.Enabled)
FormsAuthentication.SignOut();
}
}
到目前为止一切顺利。我遇到的问题是,如果管理员更改用户的角色或时区,则下次他们返回站点时,他们的票证不会更新(如果他们选择在登录时记住我的话)。
这是我的身份验证设置,有助于:
<authentication mode="Forms">
<forms timeout="10080" slidingExpiration="true" />
</authentication>
<membership userIsOnlineTimeWindow="15" />
我一直在阅读有关slidingExpiration的内容,但据我所知,它只会增加到期时间,并且不会续订Cookie的内容。如果有人可以提供帮助,我真的很感激。感谢
答案 0 :(得分:1)
我只是将Session_Start更改为:
// If the user is disabled then log them out else update their ticket
if (Request.IsAuthenticated)
{
var user = _userRepository.Single(u => u.UserName == HttpContext.Current.User.Identity.Name);
if (!user.Enabled)
FormsAuthentication.SignOut();
else
RenewTicket(); // This calls the same code to create the cookie as used when logging in
}
答案 1 :(得分:0)
我的建议是为记忆做另一个cookie。 这样会话信息可以是内存中的cookie,同时记住我可以将cookie设置为持久存在。