Add B2C to Blazor Application

Summary

Adding Azure B2C Authentication & Authorisation has been simplified in Visual Studio 2022. The following post describes how to get a Blazor application connected to and authenticated with Azure B2C.

Create a new Blazor Server App

  1. In Visual Studio 2022, create a new Blazor Server App.
  2. Add authentication, and select the Azure AD B2C Tenant, to complete the wizard.

Note, do not enable the following when going through the wizard:

Add Server Configuration

Remove all or any Redirect URIs and add the same applicationUrl documented in the launchSettings.json

    "Client": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7155;http://localhost:5155",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
{
   https://localhost:7015/signin-oidc
}

Finally, update the Implicit grant and hybrid flows section to the following:

Update configuration

Update the Program.cs class, adding the following IdentityModelEventSource.ShowPII = true;

app.MapFallbackToPage("/_Host");
IdentityModelEventSource.ShowPII = true;

app.Run();

Update the applicationsettings.json with the following details. In particular, the SignUpSignInPolicyId.

{
  "AzureAd": {
    "Instance": "https://eax360org.b2clogin.com/",
    "Domain": "eax360org.onmicrosoft.com",
    "TenantId": "00012000-5555-5555-00a00-002019291038",
    "ClientId": "01928472-1234-3201-29101-071529966ce4",
    "CallbackPath": "/signin-oidc",
    "SignUpSignInPolicyId": "B2C_1_m1"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}