【问题标题】:Identity Authorize Attribute Roles with Web API使用 Web API 对属性角色进行身份授权
【发布时间】:2014-12-22 06:35:24
【问题描述】:

我有一个小型 Web API 应用程序,它使用 Identity 来管理使用 Owin Bearer 令牌的用户。此实现的基础工作正常:我可以注册用户、登录用户并访问标有[Authorize] 的 Web API 端点。

我的下一步是使用角色来限制 Web API 端点。例如,只有管理员角色的用户才能访问的控制器。我已经创建了如下的管理员用户,并将它们添加到管理员角色。但是,当我将现有控制器从 [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;
        }
    }

问:设置和使用角色的正确方法是什么?


【问题讨论】:

  • 您是否检查了新创建的角色“管理员”的角色表和具有管理员角色的正确用户的用户角色表?您使用的是身份框架 2.0 还是更高版本?

标签: asp.net asp.net-web-api asp.net-identity asp.net-web-api2


【解决方案1】:

您如何在用户登录时为他们设置声明我相信您在方法 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 结合起来吗?在授予中,如果用户属于该角色,我是否应该只将声明分配给身份?如果您能指出一些文档,我将不胜感激。谢谢!
  • 已更新答案,请查看
  • 我是 Claims 令牌的新手,但在我看来,从服务器收到的所有令牌都将分配有管理员和主管角色。身份的角色不应该由该用户拥有的角色动态获取吗?
  • @Mohag519 你错过了一点:想法是向身份添加类型为 ClaimTypes.Role 的声明。而已。添加额外的逻辑/验证/检查/等完全取决于您。
猜你喜欢
  • 2020-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 2014-07-19
  • 2010-11-25
  • 1970-01-01
相关资源
最近更新 更多