Reputation: 9386
In my ASP.NET Core 1.1 application I'm using JWT tokens for authentication. Under certain conditions I need to add additional claims to the user which are not provided in the token.
So I hooked into the IJwtBearerEvents.TokenValidated
event and tried to add additional claims in that event handler. I tried several things:
// (1) - doesn't work
((ClaimsIdentity)context.HttpContext.User.Identity).AddClaim(myNewClaim);
// (2) - doesn't work
var jwtToken = context.SecurityToken as JwtSecurityToken;
((ICollection<Claim>)jwtToken.Claims).Add(myNewClaim);
// (3) - doesn't work
context.HttpContext.User.AddIdentity(new ClaimsIdentity(new Claim[] { myNewClaim }));
No matter how I do it, I don't see these additional claims in User.Claims
in the controller action.
What is the correct way to add additional claims after successful bearer token verification?
Upvotes: 2
Views: 3271
Reputation: 9386
The article linked by @MarkG shows a fourth way for accessing the claims - and this one works:
// (4) - works!
(context.Ticket.Principal.Identity as ClaimsIdentity).AddClaim(myNewClaim);
Upvotes: 3