身份授权属性使用Web API角色 [英] Identity Authorize Attribute Roles with Web API

查看:167
本文介绍了身份授权属性使用Web API角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用标识使用Owin承载令牌来管理用户一个小型的Web API应用程序。这个实施做工精细的基础知识:我可以将用户注册,登录标有用户和访问的Web API终点[授权]

I have a small Web API application that uses Identity to manage users using Owin Bearer Tokens. The basics of this implementation work fine: I can register a user, login a user and access Web API end points that are marked with [Authorize].

我的下一个步骤是限制使用角色的Web API端点。例如,控制器,只有在管理员角色的用户可以访问。我创建了如下管理员用户,我将它们添加到管理角色。然而,当我从更新现有的控制器[授权] [授权(角色=管理员)] ,并尝试使用ADIM帐户来访问它,我得到一个 401未授权

My next step is to limit Web API endpoints using roles. For example, a controller that only users in the Admin role can access. I've created the Admin user as below and I add them to the Admin role. However when I update my existing controllers from [Authorize] to [Authorize(Roles = "Admin")] and try to access it using the Adim account, I get a 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;
        }
    }


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

推荐答案

如何设置对用户的要求,当他们登录我相信你缺少的方法,这行code的 GrantResourceOwnerCredentials

How do you set the claims for the users when they login I believe you are missing this line of code in method 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"));

如果你想创建数据库的身份使用如下:

And if you want to create the identity from DB use the below:

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

这篇关于身份授权属性使用Web API角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆