当用户登录到我的站点时,我创建以下身份验证票据:
// 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的内容。如果有人能帮忙,我会非常感激的。谢谢