基于角色的授权在asp核心2中使用jwt令牌和身份

时间:2017-10-29 16:16:15

标签: c# asp.net-core authorization jwt asp.net-core-identity

我在asp核心2中尝试了一些授权示例,其中包含jwt令牌和asp核心身份。我已经遵循了这段代码https://github.com/SunilAnthony/SimpleSecureAPI,它运行正常。

问题是基于角色的授权。我试过这样的事情: http://www.jerriepelser.com/blog/using-roles-with-the-jwt-middleware/

结果很奇怪。 我的控制器方法:

[HttpGet]
[Authorize]
public IActionResult Get()
{
    IEnumerable<Claim> claims = User.Claims; // contains claim with Type = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" and Value = "Administrator"
    bool role = User.IsInRole("Administrator"); // true
    bool claim = User.HasClaim(ClaimTypes.Role, "Administrator"); // true

    return Ok(claims);
} 

当我使用属性[Authorize]调用此端点并在代码中检查当前用户的角色/声明时,它似乎很好(两个检查都是真的),但是当我将授权属性更改为[Authorize(Roles = "Administrator")]时它不起作用 - &gt; 当我使用此属性调用此终结点时,我将收到404 。我不知道问题出在哪里。我的启动类与上面的git链接完全相同,我刚刚在“roles”数组中的access_token的有效负载中添加了字符串角色名称列表:

它是硬编码的,但我已经改变了我的登录方法,只是为了这样的测试:

[HttpPost("login")]
public async Task<IActionResult> SignIn([FromBody] Credentials Credentials)
{
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(Credentials.Email, Credentials.Password, false, false);
        if (result.Succeeded)
        {
            IdentityUser user = await _userManager.FindByEmailAsync(Credentials.Email);

            List<string> roles = new List<string>();
            roles.Add("Administrator");

            return new JsonResult(new Dictionary<string, object>
                {
                    { "access_token", GetAccessToken(Credentials.Email, roles) },
                    { "username", user.Email },
                    { "expired_on", DateTime.UtcNow.AddMinutes(_tokenLength) },
                    { "id_token", GetIdToken(user) }
                });
        }
        return new JsonResult("Unable to sign in") { StatusCode = 401 };
    }
    return new JsonResult("Unable to sign in") { StatusCode = 401 };
}

GetAccessTokenMethod

private string GetAccessToken(string Email, List<string> roles)
{
  var payload = new Dictionary<string, object>
  {
    { "sub", Email },
    { "email", Email },
    { "roles", roles },
  };
  return GetToken(payload);
}

[Authorize(Roles = "Administrator")]属性的问题在哪里?

1 个答案:

答案 0 :(得分:0)

问题出在声明的类型上

http://schemas.microsoft.com/ws/2008/06/identity/claims/role

不知何故,[Authorize]属性与Roles值一起使用时无法正常工作。 因此,此[Authorize(Roles = "Administartor")]不起作用。 您必须通过对role类应用转换来将声明类型仅映射到Startup

如果您有一个基于Owin的项目:

app.UseClaimsTransformation(incoming =>
            {
                // either add claims to incoming, or create new principal
                var appPrincipal = new ClaimsPrincipal(incoming);
                if (appPrincipal.HasClaim(x => x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role"))
                {
                    var value = appPrincipal.Claims.First(x =>
                        x.Type == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role").Value;

                    incoming.Identities.First().AddClaim(new Claim("role", value));
                }                

                return Task.FromResult(appPrincipal);
            });