Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c# - Can't access Roles in JWT Token .NET Core

I have an application made with .NET Core API, Keycloak and JWT Token.

The older version of Keycloak that I've been using so far, when it created the JWT Token it wrote the roles here on payload:

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

But now after I updated it, it's writing the roles here on payload:

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

And I need to know how to change this old code to the new one, to tell that don't look at user_roles, but do look at realm_access then to 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")
                          ))
        );
    });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The following code will transform "realm_access.roles"-claim (JWT Token) from Keycloak (v4.7.0) into Microsoft Identity Model role-claims:

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(ClaimTypes.Role, role));
                }
            }
        }

        return Task.FromResult(principal);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...