无法访问JWT令牌.NET Core中的角色

时间:2018-12-10 09:17:08

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

我有一个使用.NET Core API,Keycloak和JWT令牌制作的应用程序。

到目前为止,我一直使用的较旧版本的Keycloak,当它创建JWT令牌时,就在有效负载上写了角色:

{
    "user_roles": [
        "offline_access",
        "uma_authorization",
        "admin",
        "create-realm"
  ]
}

但是现在我更新了它之后,就在有效负载上写了角色:

{
  "realm_access": {
    "roles": [
      "create-realm",
      "teacher",
      "offline_access",
      "admin",
      "uma_authorization"
    ]
  },
}

我需要知道如何将旧代码更改为新代码,以告诉您不要先看user_roles,而要先看realm_access然后再看roles

public void AddAuthorization(IServiceCollection services)
{
    services.AddAuthorization(options =>
    {
        options.AddPolicy("Administrator", policy => policy.RequireClaim("user_roles", "admin"));
        options.AddPolicy("Teacher", policy => policy.RequireClaim("user_roles", "teacher"));
        options.AddPolicy("Pupil", policy => policy.RequireClaim("user_roles", "pupil"));
        options.AddPolicy(
            "AdminOrTeacher",
            policyBuilder => policyBuilder.RequireAssertion(
                context => context.User.HasClaim(claim =>
                               claim.Type == "user_roles" && (claim.Value == "admin" || claim.Value == "teacher")
                          ))
        );
    });
}

2 个答案:

答案 0 :(得分:3)

以下代码会将“ realm_access.roles”声明(JWT令牌)从Keycloak(v4.7.0)转换为Microsoft身份模型角色声明:

public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient<IClaimsTransformation, ClaimsTransformer>();
    ...
}

public class ClaimsTransformer : IClaimsTransformation
{
    public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        ClaimsIdentity claimsIdentity = (ClaimsIdentity)principal.Identity;

        // flatten realm_access because Microsoft identity model doesn't support nested claims
        // by map it to Microsoft identity model, because automatic JWT bearer token mapping already processed here
        if (claimsIdentity.IsAuthenticated && claimsIdentity.HasClaim((claim) => claim.Type == "realm_access"))
        {
            var realmAccessClaim = claimsIdentity.FindFirst((claim) => claim.Type == "realm_access");
            var realmAccessAsDict = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(realmAccessClaim.Value);
            if (realmAccessAsDict["roles"] != null)
            {
                foreach (var role in realmAccessAsDict["roles"])
                {
                    claimsIdentity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", role));
                }
            }
        }

        return Task.FromResult(principal);
    }
}

答案 1 :(得分:0)

对于任何未来的读者 - 您可以使用 RequireAssertion 方法解析来自 JWT 的任何声明值。

services.AddAuthorization(options => options.AddPolicy("Administrator", policy =>
   policy.RequireAssertion(c =>
        JsonSerializer.Deserialize<Dictionary<string, string[]>>(c.User?.FindFirst((claim) => claim.Type == "realm_access")?.Value ?? "{}")
             .FirstOrDefault().Value?.Any(v => v == "admin") ?? false)));