Blazor WebAssembly Authentication with Azure AD

On this page

Securing a Single Page Application (SPA) can be tricky. Blazor WebAssembly makes it easier by providing built-in integration with OpenID Connect (OIDC) providers, including Azure Active Directory (AAD). Here is how to secure your app.

App Registration

First, register your app in the Azure Portal. 1. Create a “Single-page application” registration. 2. Set the Redirect URI to https://localhost:5001/authentication/login-callback. 3. Note the Client ID.

Configuration

Install Microsoft.Authentication.WebAssembly.Msal. Add settings to wwwroot/appsettings.json:

JSON7 lines
{
  "AzureAd": {
    "Authority": "https://login.microsoftonline.com/{TENANT_ID}",
    "ClientId": "{CLIENT_ID}",
    "ValidateAuthority": true
  }
}

Program.cs Setup

C#7 lines
builder.Services.AddMsalAuthentication(options =>
{
    builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication);
    
    // Request API scopes
    options.ProviderOptions.DefaultAccessTokenScopes.Add("api://my-api/read");
});

Protecting UI

Use the AuthorizeView component to show/hide content:

Razor8 lines
<AuthorizeView>
    <Authorized>
        <h1>Welcome, @context.User.Identity.Name!</h1>
    </Authorized>
    <NotAuthorized>
        <a href="authentication/login">Log In</a>
    </NotAuthorized>
</AuthorizeView>

Access Tokens

The best part? Blazor’s HttpClient factory automatically attaches the Bearer token to outgoing API requests when you use AddHttpClient with BaseAddressAuthorizationMessageHandler. It handles token refresh silently.


Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.