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
- An Azure account with an active subscription. Create an account for free.
- .NET 5.0 SDK or later. Install the latest .NET 5.0 SDK for your platform.
Preparation
Create a new ASP.NET Core Razor pages app:
dotnet new razor -o azure-ad-b2cThe 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.
Create a web app registration in the tenant. For Redirect URI, use
https://localhost:5001/signin-oidc. Replace5001with the port used by your app when using Visual Studio generated ports.
Modify the app
Add the
Microsoft.Identity.WebandMicrosoft.Identity.Web.UIpackages 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.0In the preceding:
Microsoft.Identity.Webincludes the basic set of dependencies for authenticating with the Microsoft Identity platform.Microsoft.Identity.Web.UIincludes UI functionality encapsulated in an area namedMicrosoftIdentity.
Add an
AzureB2Cobject toappsettings.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.
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
Accountcontroller in theMicrosoftIdentityarea.
- The link points to an action method on the
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.cshtmlpartial view in every page request that uses this layout.In
Startup.cs, make the following changes:Add the following
usingdirectives:using Microsoft.Identity.Web; using Microsoft.Identity.Web.UI; using Microsoft.AspNetCore.Authentication.OpenIdConnect;The preceding code resolves references used in the next steps.
Replace
ConfigureServiceswith 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
AddAuthenticationandAddMicrosoftIdentityWebAppmethods configure the app to use Open ID Connect, specifically configured for the Microsoft Identity platform. AddAuthorizationinitializes ASP.NET Core authorization.- The
AddRazorPagescall configures the app so anonymous browsers can view the Index page. All other requests require authentication. AddMvcOptionsandAddMicrosoftIdentityUIadd the required UI components for redirecting to/from Azure AD B2C.
- Calls to the
Add the highlighted line to the
Configuremethod: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
Run the app.
dotnet runBrowse 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.
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:
- Customize the Azure AD B2C user interface.
- Configure password complexity requirements.
- Enable multi-factor authentication.
- Configure additional identity providers, such as Microsoft, Facebook, Google, Amazon, Twitter, and others.
- Use the Microsoft Graph API to retrieve additional user information, such as group membership, from the Azure AD B2C tenant.
- How to secure a Web API built with ASP.NET Core using the Azure AD B2C.
- Tutorial: Grant access to an ASP.NET web API using Azure Active Directory B2C.
Feedback
Issottometti u ara feedback għal