2008-12-12 27 views
3

在自定義角色提供.NET 2.0中(從RoleProvider繼承),該方法的isUserInRole已硬編碼爲總是返回true:Roles.IsUserInRole在以下簡單場景中的行爲與預期相符嗎?

public override bool IsUserInRole(string username, string roleName) { return true; } 

在配置爲使用該角色提供一個ASP.NET應用程序,以下代碼返回true(如預期):

Roles.IsUserInRole("any username", "any rolename"); // results in true 

但是,下面的代碼返回false:

Roles.IsUserInRole("any rolename"); // results in false 

ñ注意User.IsInRole(「任何角色名稱」)也返回false。

  1. 這是預期的行爲?
  2. 假設僅使用角色名稱的重載仍然會調用重寫的IsUserInRole,這是不正確的嗎?

更新:請注意,似乎沒有可用於接受單個字符串,這導致了我在#2假設的版本重寫。

回答

3

我看着Roles.IsUserInRole(字符串角色名)在.NET反射器,並將其解析爲以下幾點:

public static bool IsUserInRole(string roleName) 
{ 
    return IsUserInRole(GetCurrentUserName(), roleName); 
} 

我想看看你的當前用戶。這裏的原因:

private static string GetCurrentUserName() 
{ 
    IPrincipal currentUser = GetCurrentUser(); 
    if ((currentUser != null) && (currentUser.Identity != null)) 
    { 
     return currentUser.Identity.Name; 
    } 
    return string.Empty; 
} 

我願意賭這是返回一個空字符串,因爲你要麼沒有當前用戶,或者它的名字是一個空字符串或空。

IsUserInRole(string username, string roleName)方法,有代碼,臨近開頭以下塊:

if (username.Length < 1) 
    { 
     return false; 
    } 

如果您GetCurrentUserName()不返回任何有意義的東西,那麼它將返回false它調用您的重寫方法之前。

道德從此帶走:反射是一個偉大的工具:)

+0

非常感謝!我現在已經下載了Reflector工具,謝謝你指點我。你對用戶名是空白是正確的,我使用匿名身份驗證,導致身份是System.Security.Principal.GenericIdentity,恰好有一個空白的Name屬性。 – 2008-12-12 16:41:27

0

如果您在RoleManager配置選擇cacheRolesInCookie =「真」同樣要小心了。如果您已向數據庫添加新角色,則可能正在查看Cookie中的緩存版本。

我有這個問題,解決辦法是刪除cookie並重新登錄。

0

這可能幫助別人 - 注意:

如果您正在使用的登錄控制認證 - 輸入控制的用戶名成爲其在角色中使用的HttpContext.Current.User.Identity.Name。 IsUserInRole(字符串角色名),更具體地說 - 成員的GetUser()方法。因此,如果是這種情況,請確保覆蓋Authenticate事件,使用此方法驗證用戶並將用戶名設置爲自定義成員資格提供程序可以使用的值。

protected void crtlLoginUserLogin_Authenticate(object sender, AuthenticateEventArgs e) 
{ 
    bool blnAuthenticate = false; 
    string strUserName = crtlLoginUserLogin.UserName; 

    if (IsValidEmail(strUserName)) 
    { 

     //if more than one user has email address - must authenticate by username. 

     MembershipUserCollection users = Membership.FindUsersByEmail(strUserName); 
     if (users.Count > 1) 
     { 
      crtlLoginUserLogin.FailureText = "We are unable to determine which account is registered to that email address. Please enter your Username to login."; 

     } 
     else 
     { 
      strUserName = Membership.GetUserNameByEmail(strUserName); 
      blnAuthenticate = Membership.ValidateUser(strUserName, crtlLoginUserLogin.Password); 

      //setting the userLogin to the correct user name (only on successful authentication) 
      if (blnAuthenticate) 
      { 
       crtlLoginUserLogin.UserName = strUserName; 
      } 

     } 


    } 
    else 
    { 
     blnAuthenticate = Membership.ValidateUser(strUserName, crtlLoginUserLogin.Password); 
    } 

    e.Authenticated = blnAuthenticate; 

} 
相關問題