I'm trying to add custom claims to my Blazor Server (.NET 8) application, for which I am using the IClaimsTransformation.
public class MyClaimsTransformation() : IClaimsTransformation{ public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { if (!principal.HasClaim(claim => claim.Type == "TEST")) { ((ClaimsIdentity)principal.Identity).AddClaim(new Claim("TEST", "TESTVALUE")); } return principal; }}The TransformAsync method gets called multiple times, which is apparently normal, according to other topics I found on stackoverflow.
However, I would expect the second call to the TransformAsync method it would already have the claim with type TEST. But it does not, I have to add the claim every single time.
Any idea what's going on here?
Note: I have found 2 ways of adding custom claims. One is by adding claims to the current identity, and the second is by adding a new identity. I have tried both, neither work.
Authentication is set up as follows, using OpenID Connect:
services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = "oidc"; }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.AccessDeniedPath = "/statuscode/401"; }) .AddOpenIdConnect("oidc", options => { options.Authority = configuration["Security:Authority"]; options.MetadataAddress = configuration["Security:MetadataAddress"]; options.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet; options.ClientId = configuration["Security:ClientId"]; options.ClientSecret = configuration["Security:ClientSecret"]; options.ResponseType = configuration["Security:ResponseType"]; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.UseTokenLifetime = false; options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("email"); options.UsePkce = true; });