2014-03-28 46 views
0

從.net版本3.5升級到4.5後,FormsAuthentication中的角色停止工作。用戶通過身份驗證,但該框架似乎沒有提取角色信息,並且用戶被拒絕訪問管理員。角色在FormsAuthentication停止工作

下面是在用戶登錄的代碼:

 int timeout = int.Parse(ConfigurationManager.AppSettings["loginTimeoutMinutes"]); 

     HttpContext.Current.Session.Timeout = timeout; 

     FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
      1, 
      username, 
      DateTime.Now, 
      DateTime.Now.AddMinutes(timeout), 
      false, 
      roles, 
      FormsAuthentication.FormsCookiePath); 

     string hash = FormsAuthentication.Encrypt(ticket); 
     HttpCookie cookie = new HttpCookie(
      FormsAuthentication.FormsCookieName, // Name of auth cookie 
      hash); // Hashed ticket 

     if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; 

     HttpContext.Current.Response.Cookies.Add(cookie); 

在Global.asax中此代碼,則更新角色信息的當前用戶。當我調試,我可以看到該角色爲admin:

protected void Application_AuthenticateRequest(object sender, EventArgs e) 
    { 
     if (HttpContext.Current.User != null) 
     { 
      if (HttpContext.Current.User.Identity.IsAuthenticated && 
       HttpContext.Current.User.Identity is FormsIdentity) 
      { 

       FormsIdentity id = (FormsIdentity) HttpContext.Current.User.Identity; 
       FormsAuthenticationTicket ticket = id.Ticket; 

       string userData = ticket.UserData; 
       string[] roles = userData.Split(','); 
       HttpContext.Current.User = new GenericPrincipal(id, roles); 
      } 
     } 
    } 

這裏是主要的web.config的認證比特:

<roleManager enabled="true"></roleManager> 
    <authentication mode="Forms"> 
    <forms name="theForm" loginUrl="/login.aspx"/> 
    </authentication> 

在用戶登錄後會被重定向到一個文件夾中具有以下web.config

<?xml version="1.0"?> 
<configuration> 
    <appSettings/> 
    <connectionStrings/> 
    <system.web> 
    <authorization> 
     <allow roles="admin" /> 
     <deny users="*"/> 
    </authorization> 
    </system.web> 
</configuration> 

當調試一切都看起來不錯,但用戶將被拒絕訪問管理頁面。

我錯過了什麼嗎?幫助表示讚賞。 (我知道這個問題以前被問過,但我已經閱讀了大約50個問題/答案在這裏stackoverflow和嘗試所有的建議沒有找到答案)

(另一個奇怪的是,升級後的.net版本,我不得不添加

<add key="enableSimpleMembership" value="false"/> 

到web.config中得到重定向到正確的登錄頁。)

回答

0

#1的好心人!

我使用了錯誤的EventHandler。要使用的是PostAuthenticateRequest

我十分誠摯地向十八個讀過這個問題的人致歉,他們浪費了我的時間。