Cloud authentication with Azure Active Directory B2C in ASP.NET Core

Azure Active Directory B2C (Azure AD B2C) is a cloud identity management solution for web and mobile apps. The service provides authentication for apps hosted in the cloud and on-premises. Authentication types include individual accounts, social network accounts, and federated enterprise accounts. Additionally, Azure AD B2C can provide multi-factor authentication with minimal configuration.

Tip

Azure Active Directory (Azure AD) and Azure AD B2C are separate product offerings. An Azure AD tenant generally represents an organization, while an Azure AD B2C tenant represents a collection of identities to be used with relying party applications. To learn more, see Azure AD B2C: Frequently asked questions (FAQ).

In this tutorial, you'll learn how to configure an ASP.NET Core app for authentication with Azure AD B2C.

Prerequisites

Preparation

  1. Create an Azure Active Directory B2C tenant.

  2. Create a new ASP.NET Core Razor pages app:

    dotnet new razor -o azure-ad-b2c
    

    The previous command creates a Razor pages app in a directory named azure-ad-b2c.

    Tip

    You may prefer to use Visual Studio to create your app.

  3. Create a web app registration in the tenant. For Redirect URI, use https://localhost:5001/signin-oidc. Replace 5001 with the port used by your app when using Visual Studio generated ports.

Modify the app

  1. Add the Microsoft.Identity.Web and Microsoft.Identity.Web.UI packages to the project. If you're using Visual Studio, you can use NuGet Package Manager.

    dotnet add package Microsoft.Identity.Web --version 1.4.0 
    dotnet add package Microsoft.Identity.Web.UI --version 1.4.0
    

    In the preceding:

    • Microsoft.Identity.Web includes the basic set of dependencies for authenticating with the Microsoft Identity platform.
    • Microsoft.Identity.Web.UI includes UI functionality encapsulated in an area named MicrosoftIdentity.
  2. Add an AzureB2C object to appsettings.json.

    {
      "AzureB2C": {
        "Instance": "https://login.microsoftonline.com/",
        "Domain": "contoso.onmicrosoft.com",
        "ClientId": "99999999-9999-9999-9999-999999999999",
        "TenantId": "common",
        "CallbackPath": "/signin-oidc"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }
    
    • For Domain, use the domain of your Azure AD B2C tenant.
    • For ClientId, use the Application (client) ID from the app registration you created in your tenant.
    • Leave all other values as they are.

    Note

    If using Azure B2C user flows, you need to set the Instance and the PolicyId of the type of flow.

    {
      "AzureAdB2C": {
        "Instance": "https://fabrikamb2c.b2clogin.com",
        "Domain": "fabrikamb2c.onmicrosoft.com",
        "ClientId": "99999999-9999-9999-9999-999999999999",
        "TenantId": "99999999-9999-9999-9999-999999999999",
        "SignedOutCallbackPath ": "/signout-callback-oidc",
        "SignUpSignInPolicyId": "your-user-flow"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }
    
    • For Domain, use the domain of your Azure AD B2C tenant.
    • For ClientId, use the Application (client) ID from the app registration you created in your tenant.
    • For Instance, use the domain of your Azure AD B2C tenant.
    • For SignUpSignInPolicyId, use the user flow policy defined in the Azure B2C tenant
    • Leave all other values as they are.
  3. In Views/Shared, create a file named _LoginPartial.cshtml. Include the following code:

    @using System.Security.Principal
    
    <ul class="navbar-nav">
    @if (User.Identity.IsAuthenticated)
    {
            <li class="nav-item">
                <span class="navbar-text text-dark">Hello @User.Identity.Name!</span>
            </li>
            <li class="nav-item">
                <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignOut">Sign out</a>
            </li>
    }
    else
    {
            <li class="nav-item">
                <a class="nav-link text-dark" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Sign in</a>
            </li>
    }
    </ul>
    

    The preceding code:

    • Checks if the user is authenticated.
    • Renders a Sign out or Sign in link as appropriate.
      • The link points to an action method on the Account controller in the MicrosoftIdentity area.
  4. In Views/Shared/_Layout.cshtml, add the highlighted line within the <header> element:

    <header>
        <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
            <div class="container">
                <a class="navbar-brand" asp-area="" asp-page="/Index">azure_ad_b2c</a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                        aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                    <partial name="_LoginPartial" />
                    <ul class="navbar-nav flex-grow-1">
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Index">Home</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
    </header>
    

    Adding <partial name="_LoginPartial" /> renders the _LoginPartial.cshtml partial view in every page request that uses this layout.

  5. In Startup.cs, make the following changes:

    1. Add the following using directives:

      using Microsoft.Identity.Web;
      using Microsoft.Identity.Web.UI;
      using Microsoft.AspNetCore.Authentication.OpenIdConnect;
      

      The preceding code resolves references used in the next steps.

    2. Replace ConfigureServices with the following code:

      public void ConfigureServices(IServiceCollection services)
      {
          services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
              .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureB2C"));
      
          services.AddAuthorization(options =>
          {
              // By default, all incoming requests will be authorized according to 
              // the default policy
              options.FallbackPolicy = options.DefaultPolicy;
          });
          services.AddRazorPages(options => {
                      options.Conventions.AllowAnonymousToPage("/Index");
                  })
              .AddMvcOptions(options => { })
              .AddMicrosoftIdentityUI();
      }
      

      In the preceding code:

      • Calls to the AddAuthentication and AddMicrosoftIdentityWebApp methods configure the app to use Open ID Connect, specifically configured for the Microsoft Identity platform.
      • AddAuthorization initializes ASP.NET Core authorization.
      • The AddRazorPages call configures the app so anonymous browsers can view the Index page. All other requests require authentication.
      • AddMvcOptions and AddMicrosoftIdentityUI add the required UI components for redirecting to/from Azure AD B2C.
    3. Add the highlighted line to the Configure method:

      public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
          }
          else
          {
              app.UseExceptionHandler("/Error");
              // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
              app.UseHsts();
          }
      
          app.UseHttpsRedirection();
          app.UseStaticFiles();
      
          app.UseRouting();
      
          app.UseAuthentication();
          app.UseAuthorization();
      
          app.UseEndpoints(endpoints =>
          {
              endpoints.MapRazorPages();
              endpoints.MapControllers();
          });
      }
      

      The preceding code enables authentication in ASP.NET Core.

Run the app

  1. Run the app.

    dotnet run
    
  2. Browse to the app's secure endpoint, for example, https://localhost:5001/.

    • The Index page renders with no authentication challenge.
    • The header includes a Sign in link because you're not authenticated.
  3. Select the Privacy link.

    • The browser is redirected to your tenant's configured authentication method.
    • After signing in, the header displays a welcome message and a Sign out link.

Next steps

In this tutorial, you learned how to configure an ASP.NET Core app for authentication with Azure AD B2C.

Now that the ASP.NET Core app is configured to use Azure AD B2C for authentication, the Authorize attribute can be used to secure your app. Continue developing your app by learning to: