8

我有一個小型Web API應用程序,它使用Identity來管理使用Owin無記名令牌的用戶。此實現的基本功能正常工作:我可以註冊用戶,登錄用戶並訪問標記爲[Authorize]的Web API端點。身份通過Web API授權屬性角色

我的下一步是使用角色限制Web API端點。例如,只有管理員角色的用戶才能訪問的控制器。我已經創建瞭如下的Admin用戶,並將他們添加到Admin角色。但是,當我將現有的控制器從[Authorize]更新爲[Authorize(Roles = "Admin")]並嘗試使用Adim帳戶訪問它時,我得到一個401 Unauthorized

//Seed on Startup 
    public static void Seed() 
    { 
     var user = await userManager.FindAsync("Admin", "123456"); 
     if (user == null) 
     { 
      IdentityUser user = new IdentityUser { UserName = "Admin" }; 
      var createResult = await userManager.CreateAsync(user, "123456"); 

      if (!roleManager.RoleExists("Admin")) 
       var createRoleResult = roleManager.Create(new IdentityRole("Admin")); 

      user = await userManager.FindAsync("Admin", "123456"); 
      var addRoleResult = await userManager.AddToRoleAsync(user.Id, "Admin"); 
     } 
    } 


    //Works 
    [Authorize] 
    public class TestController : ApiController 
    { 
     // GET api/<controller> 
     public bool Get() 
     { 
      return true; 
     } 
    } 

    //Doesn't work 
    [Authorize(Roles = "Admin")] 
    public class TestController : ApiController 
    { 
     // GET api/<controller> 
     public bool Get() 
     { 
      return true; 
     } 
    } 

問:什麼是設置和使用角色的正確方法?


+0

您是否檢查了角色表中新角色「管理員」和UserRole表的正確用戶的管理角色?您是否使用身份框架2.0或更高版本? – DSR 2014-10-27 10:59:22

回答

10

如何設置爲用戶的要求,當他們登錄我相信你缺少這行代碼的方法GrantResourceOwnerCredentials

var identity = new ClaimsIdentity(context.Options.AuthenticationType); 
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); 
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin")); 
identity.AddClaim(new Claim(ClaimTypes.Role, "Supervisor")); 

如果你想創建一個從數據庫使用的身份下面:

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType) 
    { 
     // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType 
     var userIdentity = await manager.CreateIdentityAsync(this, authenticationType); 
     // Add custom user claims here 
     return userIdentity; 
    } 

然後在GrantResourceOwnerCredentials做如下:

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType); 
+0

這可行,但我不知道我明白爲什麼。我需要將它與'userManager.AddToRoleAsync'結合嗎?在贈款中,如果用戶屬於該角色,我是否應該僅將身份索賠分配給身份?如果你能指點我一些文檔,我會很感激。謝謝! – 2014-10-28 07:36:01

+1

更新了答案,請檢查它 – 2014-10-28 08:55:33

+2

我是新來的索賠令牌,但對我來說,它看起來像從服務器收到的所有令牌都將分配管理員和主管角色。該用戶的角色是否應該動態獲取標識的角色? – Mohag519 2015-01-28 09:54:45