We are trying to implement using Azure B2C in a green field project using Microsoft.Identiy.UI 3.1.4 in a .NET Core 3.1 web application. We would like at add additional code to the OnTokenValidated event to handle getting new users set up and adding additional roles to their claims.
It seems the only way we are able to do this is the following :
services.AddSignIn(options =>
{
Configuration.Bind("AzureAD", options);
options.Events.OnTokenValidated = async context =>
{
//custom logic here
};
}, options =>
{
Configuration.Bind("AzureAD", options);
})
.AddWebAppCallsProtectedWebApi(Configuration, initialScopes: new string[] { Configuration["Api:Scope"] })
.AddInMemoryTokenCaches();
We would like to use a delegate though just to make the Startup file as small as possible and to help simplify testing. However, no matter what we try
Nothing seems to fire off our class when we are debugging .. and we cannot seem to find an example of this in the docs.
Are we just missing something on how this is to be performed?
or is this just not a supported scenario?
We're on the struggle bus currently :)
Hi @ArieJones. Yes, that's the place where you want to add custom logic. We are actually working on adding this bit to the docs. cc: @TiagoBrenck
Your code can look something like this, if you want to use a function:
services.AddSignIn(options =>
{
Configuration.Bind("AzureAD", options);
options.Events ??= new OpenIdConnectEvents();
options.Events.OnTokenValidated += OnTokenValidatedFunc;
}, options =>
{
Configuration.Bind("AzureAD", options);
})
.AddWebAppCallsProtectedWebApi(Configuration, initialScopes: new string[] { Configuration["Api:Scope"] })
.AddInMemoryTokenCaches();
private async Task OnTokenValidatedFunc(TokenValidatedContext context)
{
// Custom code
await Task.CompletedTask.ConfigureAwait(false);
}
In the above code, your handler will be executed after any existing handlers. In the below code, your code should be executed before any other existing handlers.
...
Configuration.Bind("AzureAD", options);
options.Events ??= new OpenIdConnectEvents();
var existingHandlers = options.Events.OnTokenValidated;
options.Events.OnTokenValidated = OnTokenValidatedFunc;
options.Events.OnTokenValidated += existingHandlers;
...
Hellzzzzzzz yeah! That's it!
Just confirmed via debug session.
Thanks for the assist!
Thanks for the question @ArieJones
This is now documented in https://github.com/AzureAD/microsoft-identity-web/wiki/Web-Apps#using-delegate-events
cc; @pmaytak @jennyf19 @TiagoBrenck
Most helpful comment
Thanks for the question @ArieJones
This is now documented in https://github.com/AzureAD/microsoft-identity-web/wiki/Web-Apps#using-delegate-events
cc; @pmaytak @jennyf19 @TiagoBrenck