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("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", role)); } } } return Task.FromResult(principal); }} 这篇关于无法访问JWT令牌.NET Core中的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-26 12:49