How to get notification of authentication in Blazor Server?

Brian J Hoskins 46 Reputation points
2022-03-10T16:29:45.133+00:00

I have a Blazor Server application which is configured for Authentication. There is an app registration in Azure which facilitates this. The Program.cs file sets up the authentication:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

I would like to run some custom code when a user authenticates or logs out. There is a Razor component called LoginDisplay that was included with the initial project template which does something similar for displaying the user's status:

<AuthorizeView>
    <Authorized>
        @_user.Name;
        <a href="MicrosoftIdentity/Account/SignOut">Log out</a>
    </Authorized>
    <NotAuthorized>
        <a href="MicrosoftIdentity/Account/SignIn">Log in</a>
    </NotAuthorized>
</AuthorizeView>

But I want to run some procedural code depending on whether a user is Authorized or not. I tried to search for an event that could be subscribed to, but could not find anything. What is the best way to achieve this?

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,420 questions
Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
7,035 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 57,891 Reputation points
    2022-03-10T18:47:48.073+00:00

    in blazer server, there is only one blazer request

    • the index page loads (typically authenticated via cookie)
    • page assets are loaded
    • the blazer javascript opens a signal/r connection (passing the authentication token via cookie) to create the blazer app instance hosted on the server.

    the authentication token is passed to the blazer app, when the instance is started. there is no logon or logoff event.

    if the user is not logged in at start, when authenticated access is required, the blazer login logic tell the client to redirects to the login url (via javascript interop). when login redirects back to the client a new blazer server app is loaded, this time with the authentication cookie.

    to sign out, the blazer server tells the client to redirect to the sign out url. when signout redirects back, the blazer app is reloaded, but not authenticated.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful