Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add OnTokenValidated event handler when using AD B2C?

I am using Azure B2C in a ASP.NET Core 3 application, which is working perfectly. I use the following code in Startup:

services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
    .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));

I would like to handle the standard TokenValidated OpenIdConnect event, with other words I need a configuration where my event handler is set.

Examining the source code I see the class AzureAdB2COpenIDConnectEventHandlers.cs and also its usage in AzureADB2COpenIdConnectOptionsConfiguration but unfortunately both class declared to internal

Question

All I need is to have my TokenValidated handler in effect, retaining all working out of the box OpenIdConnect based AD B2C functionality, which is working currently.

Pseudo code, something like this:

options.Events = new OpenIdConnectEvents()
{
     // ...
     OnTokenValidated = MyTokenValidatedHandler
};

How can I accomplish this in a simple way?

like image 695
g.pickardou Avatar asked Dec 31 '22 13:12

g.pickardou


1 Answers

I found my answer, by searching for ["Events.OnTokenValidated" AzureAdB2C] in github, and assembled the following for my case:

// My existing code in Startup:
services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
        .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));

// My added code to handle the OnTokenValidated event
services.Configure<OpenIdConnectOptions>(AzureADB2CDefaults.OpenIdScheme, options =>
{
    var onTokenValidated = options.Events.OnTokenValidated;
    options.Events.OnTokenValidated = context =>
    {
        onTokenValidated?.Invoke(context);
        // My custom handler goes below:
like image 167
g.pickardou Avatar answered Feb 13 '23 06:02

g.pickardou