In an ASP.NET Core application, I need to enrich the AAD token claims with custom ones coming from my application database, and I've seen code implementing the IClaimsTransformation
interface to achieve this.
But it is totally bad for performance as the TransformAsync
method is getting called every time the user needs to be authorized (meaning every time a page that requires authorization is navigated) and the ClaimsPrincipal
passed to the method is always the original one meaning that claims need to be added each and every time.
I expected that claims would need to be added only once and that they would be kept/persisted for the current session. Is there any alternative to the IClaimsTransformation
interface?
Implementing the OpenIdConnectEvents.OnTokenValidated
handler seems to achieve the same result with the added advantage that your custom claims are getting persisted across requests and thus claim enrichment needs to take place only once per user authentication and not once per user authorization (per page requiring authorization).
What risk is there in implementing it this way?
builder.Services.Configure<MicrosoftIdentityOptions>(OpenIdConnectDefaults.AuthenticationScheme, options =>
{
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = tokenContext =>
{
// getting your DB connection string
var connStr = builder.Configuration.GetConnectionString("MyDatabaseConnStr");
// your claim enrichment code...
return Task.CompletedTask;
},
};
});