如何将角色基本授权应用于使用令牌基本身份验证的Web API 2应用程序?

时间:2018-03-15 11:31:58

标签: c# authentication asp.net-web-api authorization asp.net-identity

我创建了一个使用基于令牌的身份验证系统的Web API 2应用程序。我使用此tutorial来实现对应用程序的身份验证。

然后我使用种子方法将角色添加到系统中。

        protected override void Seed(TBA.Models.AuthContext context)
        {
            if (!context.Roles.Any(r => r.Name == "SuperAdmin"))
            {
                var store = new RoleStore<IdentityRole>(context);
                var manager = new RoleManager<IdentityRole>(store);
                var role = new IdentityRole { Name = "SuperAdmin" };

                manager.Create(role);
            }
        }

然后我将用户添加到用户角色。

        public async Task<IdentityResult> RegisterUser(UserModel userModel)
        {
            IdentityUser user = new IdentityUser
            {
                UserName = userModel.UserName
            };

            var result =  await _userManager.CreateAsync(user, userModel.Password);
            await _userManager.AddToRoleAsync(user.Id, userModel.UserRole);
            return result;
        }

然后我尝试访问下面的终点。

        [Authorize(Roles = "SuperAdmin")]
        [Route("GetBySuperAdmin")]
        public IHttpActionResult GetBySuperAdmin()
        {
            return Ok("Get By Super Admin");
        }

它给出了以下错误消息。

"message": "Authorization has been denied for this request."

为了使这个更正,我应该改变什么? 如何在访问Web API 2应用程序中的端点之前检查角色?

1 个答案:

答案 0 :(得分:0)

将用户添加到角色后,您必须注销然后再次登录(生成新令牌)。

令牌包含有关用户角色的信息,因此在更改角色后您必须刷新令牌,以获取有关新角色的信息。

相关问题