I am on .NET Core 3.1 and I am trying to add a custom claim to a JWT token but I am unable to do so. If you look at the code below, I am able to read the custom token using this line of Code
User.Claims.Where(x => x.Type == "role")
But when I grab the JWT token and put it in JWT.ms, the new custom claim is not present in the token. .OnTokenValidated
is the event where I attempted to add the custom claim to the token before it is returned by the idp.
AddOpenIdConnect("test",o => {
o.SignInScheme = "Cookies";
o.SignOutScheme = "Cookies";
o.ClientId = "f";
o.ClientSecret = "0e";
o.Authority = "https://test.com";
o.ResponseType = OpenIdConnectResponseType.Code;
o.MetadataAddress = "https://test.com/.well-known/openid-configuration";
**o.Events.OnTokenValidated = async (ctx) =>
{
var claimsIdentity = ctx.Principal.Identity as ClaimsIdentity;
claimsIdentity.AddClaim(new Claim("role", "Admin"));
};**
o.SaveTokens = true;
o.GetClaimsFromUserInfoEndpoint = true;
First of all, some fundamentals:
when you use this code:
claimsIdentity.AddClaim(new Claim("role", "Admin"));
You are adding it to the User (ClaimsPrincipal) that was created from the ID-Token. This claim is then typically saved in the local session cookie. So this line never modifies any tokens.
Perhaps you can try to add that claim in the authorization service?
To complement this answer, I wrote a blog post that goes into more detail about this topic: Debugging OpenID Connect claim problems in ASP.NET Core and Exploring what is inside the ASP.NET Core cookies