'How to run code after authenticating with Azure AD

I have a blazor wasm application (SPA) that uses Azure AD authentication to authenticate users using the out of the box scaffolding that the new project command creates:

e.g.

 dotnet new blazorwasm -au SingleOrg --client-id "<app id>" -o BlazorSample --tenant-id "<tenant id>"

The application needs to run code after authenticating with Azure AD. It also needs access to the access token from Azure AD.

Is there a way for my code to be called after the authentication stack has authenticated a user?



Solution 1:[1]

When configuring the options for authentication on startup, you can provide a method to run once the ticket is received.

services.Configure(OpenIdConnectDefaults.AuthenticationScheme, (Action<OpenIdConnectOptions>)(options =>
{
     options.Events.OnTicketReceived = async context =>
     { 
          var tokens = context.Result.Ticket.Properties.GetTokens();
          context.HttpContext.RequestServices.GetService<SomeService>();
          //do work here
     };
}));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 zep426