Secure Your Blazor WebAssembly App with Azure AD B2C
This sample demonstrates how to integrate Azure AD B2C authentication into a Blazor WebAssembly (WASM) application using Microsoft.AspNetCore.Components.WebAssembly.Authentication
.
Prerequisites
- .NET SDK 8.0 or later
- Visual Studio 2022 or VS Code
- Azure AD B2C tenant (free tier works)
Key Files
Below are the core snippets you need to add to your project.
Program.cs
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add("#app");
builder.Services.AddHttpClient("ServerAPI", client =>
client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
.AddHttpMessageHandler();
builder.Services.AddScoped(sp => sp.GetRequiredService()
.CreateClient("ServerAPI"));
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
options.ProviderOptions.DefaultAccessTokenScopes.Add("https://{tenant}.onmicrosoft.com/api/read");
});
await builder.Build().RunAsync();
appsettings.json
{
"AzureAdB2C": {
"Authority": "https://{tenant}.b2clogin.com/{tenant}.onmicrosoft.com/B2C_1_signupsignin",
"ClientId": "YOUR-CLIENT-ID",
"ValidateAuthority": true
}
}
_Imports.razor
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@attribute [Authorize]
Running the Sample
- Clone the repository from the GitHub source.
- Update
appsettings.json
with your Azure AD B2C values. - Run
dotnet run
from theBlazorWasmAuth
folder. - Navigate to
https://localhost:5001
and click Login to test.