Reputation: 365
I am using IdentityServer4 and OpenId to authenticate users in my MVC app and want to add claims of my own. But I am unsure which of the OpenIdConnectEvents I should do this in.
This tutorial says I that...
During the authentication flow, you might want to modify the claims that you get from the IDP. In ASP.NET Core 1.0, you can perform claims transformation inside of the AuthenticationValidated event from the OpenID Connect middleware.
Any claims that you add during AuthenticationValidated are stored in the session authentication cookie.
However this event is not available in ASP.NET Core 1.1
I have tried to do it in the TokenValidated event..
var principal = context.Request.HttpContext.User;
principal.Identities.First().AddClaim(new Claim("TenantId", user.TenantId.ToString()));
But when I list the user claims after authentication it isn't listed.
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
}
Upvotes: 2
Views: 1780
Reputation: 13704
Your approach of using the TokenValidated
event seems correct, however the way you try to add the claim is wrong.
At this point in the authentication process, the user is still not authenticated. The OpenID Connect middleware is still putting together all the information it needs. Then it will pass this information to the Cookies middleware which will materialise the authentication with a session cookie.
My point is, don't use context.Request.HttpContext.User
at this point because it doesn't contain the user authenticated via OIDC. You can rather add a claim with context.Ticket.Principal.Identities.First().AddClaim
, as this is the identity that will be passed to the Cookies middleware later.
Upvotes: 9