Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming Open Id Connect claims in ASP.Net Core

I'm writing an ASP.Net Core Web Application and using UseOpenIdConnectAuthentication to connect it to IdentityServer3. Emulating their ASP.Net MVC 5 sample I'm trying to transform the claims received back from Identity Server to remove the "low level protocol claims that are certainly not needed." In MVC 5 they add a handler for the SecurityTokenValidated Notification that swaps out the AuthenticationTicket for one with just the required claims.

In ASP.Net Core, to do the equivalent, I thought that I would need to handle the OnTokenValidated in the OpenIdConnectEvents. However, at that stage it doesn't appear that the additional scope information has been retrieved. If I handle the OnUserInformationReceived, the extra information is present, but stored on the User rather than the principal.

None of the other events seem like the obvious place to permanently remove the claims I'm not interested in retaining after authentication has completed. Any suggestions gratefully received!

like image 522
Piers Lawson Avatar asked Aug 19 '16 10:08

Piers Lawson


1 Answers

I like LeastPrivilege's suggestion to transform earlier in the process. The code provided doesn't quite work. This version does:

var oidcOptions = new OpenIdConnectOptions
{
   ...

   Events = new OpenIdConnectEvents
   {
       OnTicketReceived = e =>
       {
          e.Principal = TransformClaims(e.Ticket.Principal);
          return Task.CompletedTask;
       }
   }
};

This replaces the Principal rather than the Ticket. You can use the code from my other answer to create the new Principal. You can also replace the Ticket at the same time but I'm not sure it is necessary.

So thank you to LeastPrivilege and Adem for suggesting ways that pretty much answered my question... just the code needed slight adjustments. Overall, I prefer LeastPrivilege's suggestion of transforming claims early.

like image 57
Piers Lawson Avatar answered Sep 20 '22 12:09

Piers Lawson