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:
{
"AzureAd": {
"Authority": "https://login.microsoftonline.com/{TENANT_ID}",
"ClientId": "{CLIENT_ID}",
"ValidateAuthority": true
}
}
Program.cs Setup
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:
<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.