2010-09-21 19 views
2

當用戶登錄到我的網站我創建以下身份驗證票:ASP.NET更新的FormsAuthenticationTicket

// 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

你的web.config設置是否可以使用?這篇文章使它看起來像'不',但我不知道滑動過期:http://weblogs.asp.net/owscott/archive/2006/07/15/Forms-Authentication-Timeout.aspx – pc1oad1etter 2012-03-28 14:56:26

回答

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 
} 
0

我的建議是做另一餅乾的記憶。 這種方式會話信息可以在內存中的cookie,而記住我的cookie可以設置爲持久。