How to add OnTokenValidated event handler when using AD B2C?

半腔热情 提交于 2020-05-15 08:01:07

问题


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?


回答1:


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:


来源:https://stackoverflow.com/questions/58508727/how-to-add-ontokenvalidated-event-handler-when-using-ad-b2c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!