身份验证属性中的角色与Web API

8
我有一个小的Web API应用程序,它使用Identity管理用户,并使用Owin Bearer Tokens。这个实现的基础部分工作得很好:我可以注册用户,登录用户并访问标记有[Authorize]的Web API端点。
我的下一步是使用角色限制Web API端点。例如,只有Admin角色的用户才能访问某个控制器。我已创建了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;
        }
    }

问:如何正确设置和使用角色?



你是否检查了角色表中新创建的角色“Admin”,以及UserRole表中具有正确Admin角色的用户?你是否使用了2.0或更高版本的身份框架? - DSR
1个回答

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);

这个可以运行,但我不确定为什么。我需要将其与userManager.AddToRoleAsync结合使用吗?在授权中,如果用户属于该角色,我只应该将声明分配给身份吗?如果您能指向一些文档,我会非常感激。谢谢! - user-8564775
1
回答已更新,请查看。 - Taiseer Joudeh
2
我对Claims令牌还不熟悉,但在我看来,从服务器接收到的所有令牌都将被分配为管理员和主管角色。这个用户的身份应该动态获取其拥有的角色,而不是固定分配角色。 - Mohag519
@Mohag519 你漏掉了一个要点:这个想法是将类型为ClaimTypes.Role的声明添加到身份验证中。就是这样。完全由您自己决定是否添加额外的逻辑/验证/检查等。 - Pavel Kovalev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接