2013-09-30 164 views
5

在ASP MVC5 RC我沒有得到角色系統的工作。 我的數據庫有所有需要表的角色存在,但證明如果用戶在角色中總是返回false(無SQL異常或其他)!角色管理在ASP MVC 5(Microsoft.AspNet.Identity)

我需要在某處激活IPrincipal的角色系統嗎?

測試代碼:

AccountController accCont = new AccountController(); 

// check role exist : result = true 
var roleExist = await accCont.IdentityManager.Roles.RoleExistsAsync("61c84919-72e2-4114-9520-83a3e5f09de1"); 

// try find role by name : result = role object 
var role = await accCont.IdentityManager.Roles.FindRoleByNameAsync("ProjectAdministrator"); 

// check with AccountController instance : result = true 
var exist = await accCont.IdentityManager.Roles.IsUserInRoleAsync(User.Identity.GetUserId(), role.Id); 

// check if current user is in role : result (both) = false???? 
var inRole = User.IsInRole(role.Id); 
var inRole2 = User.IsInRole(role.Name); 

我也嘗試從Microsoft.AspNet.Identity.Owin命名空間打造像IIdentity.GetUserId()擴展方法的定製過錯。

namespace Microsoft.AspNet.Identity 
{ 
    public static class IdentityExtensions 
    { 
     public static string IsUserInRole(this IIdentity identity) 
     { 
      if (identity == null) 
      { 
       throw new ArgumentNullException("identity"); 
      } 
      ClaimsIdentity identity2 = identity as ClaimsIdentity; 
      if (identity2 != null) 
      { 
       var result = identity2.FindFirstValue(IdentityConfig.Settings.GetAuthenticationOptions().RoleClaimType); 

       return null; // later result 
      } 
      return null; 
     } 
    } 
} 

但要求類型RoleClaimType結果總是null :( 我真的堅持了這一點。

謝謝您的幫助!斯特芬

+0

你有沒有試過User.IsInRole(「字符串角色名稱」)? – nocturns2

+1

或者你可以嘗試:string [] userroles = Roles.GetRolesForUser(「username」) - 這應該返回一個userroles中的數組,您可以循環以確定它是否包含特定角色。 – nocturns2

回答

2

User.IsInRole基本上看索賠對於當前登錄的用戶來說,你的登錄邏輯是什麼樣的?這就是負責把cookie變成用戶身份的東西,這需要爲IsInRole方法正確設置角色聲明。

+0

我也需要這個! – janhartmann

+1

@JeremyCook你有沒有得到解決方案。我已經實現了一個自定義的用戶存儲,而不是使用默認的實體框架。當[Authorize(Roles =「Admin」)]執行時,角色相關的方法不會被調用 –

+0

我找到了我的問題的來源併發布了答案[here](http://stackoverflow.com/questions/20428405/爲什麼,心不是-authorizeroles管理員 - 工作 - 在-MVC-5-RTM-與-ASP淨identit/20433316#20433316)。 –

2

我想了解如何在MVC 5中使用角色我自己,這是什麼使我在這裏。我無法回答你的問題,但請查看此鏈接。下載的解決方案可以直接使用,我已經可以剪切並粘貼一些代碼並在我自己的應用程序中運行。現在我試圖完全理解它在做什麼。

http://www.typecastexception.com/post/2013/11/11/Extending-Identity-Accounts-and-Implementing-Role-Based-Authentication-in-ASPNET-MVC-5.aspx

它可能不回答你的問題,但至少這是因爲沒有很多的麻煩所描述的,所以這是一個很好的起點,它實際工作完全可行的解決方案。