MSDN Docs

Blazor WebAssembly Authentication

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.

Download Sample Project

Prerequisites

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

  1. Clone the repository from the GitHub source.
  2. Update appsettings.json with your Azure AD B2C values.
  3. Run dotnet run from the BlazorWasmAuth folder.
  4. Navigate to https://localhost:5001 and click Login to test.