I need to access a custom claim that I'm adding to the User after Authentication
In my auth server I'm adding custom claims to the response as follows
public class MyProfileService : IProfileService
{
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
var claims = new List<Claim>();
claims.Add(new Claim("MyNewClaim", "lol"));
context.IssuedClaims = claims;
On my calling client I can see that the raw token, which I inspect in OnTokenResponseReceived
, has the claim when I decode it
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Events.OnTokenResponseReceived += ctxt =>
{
ctxt.TokenEndpointResponse.AccessToken // <-- has raw token that contains claim
The calling client has a middleware component that attempts to read the claims from the User's identity:
public async Task InvokeAsync(HttpContext context)
{
var claimsIdentity = (ClaimsIdentity)context.User.Identity;
var hasNewClaim = claimsIdentity.HasClaim(c => c.Type == "MyNewClaim"); // always false
The problem I have is that the claim is never there.
Question:
What do I need to do to access the new claim in my User's Identity?
The fix was to retrieve the supplementary data from the token service's /UserInfo endpoint.
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
// stuff
options.Events.OnUserInformationReceived += context =>
{
// get UserInfo data from the context
var userInfo = JsonConvert.DeserializeObject<OpenIdConnectUserInfo>(context.User.RootElement.ToString());
// do stuff with the newly acquired info.
return Task.CompletedTask;
};
// go home and tell your kids you love them
});