身份使用Web API授权属性角色

use*_*775 8 asp.net asp.net-web-api asp.net-identity asp.net-web-api2

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

我的下一步是使用角色限制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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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


Tai*_*deh 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"));
Run Code Online (Sandbox Code Playgroud)

如果您想从DB创建标识,请使用以下内容:

 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;
    }
Run Code Online (Sandbox Code Playgroud)

然后在GrantResourceOwnerCredentials下面做:

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);
Run Code Online (Sandbox Code Playgroud)

  • 我是声明令牌的新手,但对我而言,从服务器收到的所有令牌都会分配管理员和主管角色.不应该由该用户拥有的角色动态获取身份的角色吗? (2认同)