I'm creating a POC where the user can authenticate himself via Azure AD.
It works perfectly but now I want to persist in a local database the user information (not the login/password) if is not already present.
So I need to find the right 'point' in the flow where, after a successfully authentication, the system checks if the user already exists, if not then it saves it.
Which is the best point?
I see 2 techniques:
On the login button pass a redirect url that the Microsoft server will redirect user to at the finish of the authentication flow. I don't like this way because seems too weak for me.
<a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn" asp-route-redirecturi='/Home/profile'>Sign in</a>Customize the options in AddMicrosoftIdentityWebApp to react to the event OnTicketReceived. I don't fully understand this event: I can't get if it is raised only once after the user authentication or also every time that the Authentication Token is refreshed.
builder.Services .AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(options => { builder.Configuration.Bind("AzureAdB2C", options); options.Events.OnTicketReceived += async context => { //Get the full user's profile from Azure var azureService = context.HttpContext.RequestServices.GetService<IAzureService>(); var principal = await azureService.GetProfileAsync(context.Principal).ConfigureAwait(false); //Then persist it into the Application Database var userService = context.HttpContext.RequestServices.GetService<IUserService>(); await userService.PersistAsync(principal).ConfigureAwait(false); }; }) .EnableTokenAcquisitionToCallDownstreamApi(new[] { "user.read" }) .AddInMemoryTokenCaches();
Thank you!