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