asp.net – 身份使用Web API授权属性角色

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

我的下一步是使用角色限制Web API端点.例如,只有Admin角色的用户才能访问的控制器.我已经创建了Admin用户,如下所示,我将它们添加到Admin角色.但是,当我将现有的控制器从[授权]更新为[授权(角色=“管理员”)]并尝试使用Adim帐户访问它时,我获得了401未授权.

//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;
        }
    }

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

解决方法

如何在用户登录时为其设置声明我相信您在方法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"));

如果要从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;
    }

然后在GrantResourceOwnerCredentials中执行以下操作:

ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,OAuthDefaults.AuthenticationType);

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...