Events
Power BI DataViz World Championships
Feb 14, 4 PM - Mar 31, 4 PM
With 4 chances to enter, you could win a conference package and make it to the LIVE Grand Finale in Las Vegas
Learn moreThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
By Damien Bod
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
Microsoft Entra ID, Microsoft Entra External ID and Azure AD B2C are separate product offerings. An Entra ID tenant generally represents an organization, while an Azure AD B2C tenant or a Microsoft Entra External ID tenant can represent a collection of identities to be used with relying party applications. To learn more, see Azure AD B2C: Frequently asked questions (FAQ).
Tip
Microsoft Entra External ID for customers is Microsoft’s new customer identity and access management (CIAM) solution.
In this tutorial, you'll learn how to configure an ASP.NET Core app for authentication with Azure AD B2C.
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.
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.
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
dotnet add package Microsoft.Identity.Web.UI
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
.Add an AzureADB2C
object to appsettings.json
.
Note
When using Azure B2C user flows, you need to set the Instance and the PolicyId of the type of flow.
{
"AzureADB2C": {
"Instance": "https://--your-domain--.b2clogin.com",
"Domain": "[Enter the domain of your B2C tenant, e.g. contoso.onmicrosoft.com]",
"TenantId": "[Enter 'common', or 'organizations' or the Tenant Id (Obtained from the Azure portal. Select 'Endpoints' from the 'App registrations' blade and use the GUID in any of the URLs), e.g. da41245a5-11b3-996c-00a8-4d99re19f292]",
"ClientId": "[Enter the Client Id (Application ID obtained from the Azure portal), e.g. ba74781c2-53c2-442a-97c2-3d60re42f403]",
// Use either a secret or a certificate. ClientCertificates are recommended.
"ClientSecret": "[Copy the client secret added to the app from the Azure portal]",
"ClientCertificates": [
],
// the following is required to handle Continuous Access Evaluation challenges
"ClientCapabilities": [ "cp1" ],
"CallbackPath": "/signin-oidc",
// Add your policy here
"SignUpSignInPolicyId": "B2C_1_signup_signin",
"SignedOutCallbackPath": "/signout-callback-oidc"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
In Pages/Shared, create a file named _LoginPartial.cshtml
. Include the following code:
@using System.Security.Principal
<ul class="navbar-nav">
@if (User.Identity?.IsAuthenticated == true)
{
<span class="navbar-text text-dark">Hello @User.Identity?.Name!</span>
<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:
Account
controller in the MicrosoftIdentity
area.In Pages/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-bs-toggle="collapse" data-bs-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">
<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>
<partial name="_LoginPartial" />
</div>
</div>
</nav>
</header>
Adding <partial name="_LoginPartial" />
renders the _LoginPartial.cshtml
partial view in every page request that uses this layout.
In Program.cs, make the following changes:
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.
Update the builder.Services
lines with the following code:
builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureADB2C"));
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to
// the default policy
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages(options => {
options.Conventions.AllowAnonymousToPage("/Index");
})
.AddMvcOptions(options => { })
.AddMicrosoftIdentityUI();
In the preceding code:
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.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.Update the highlighted line to the Configure
method:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
The preceding code enables authentication in ASP.NET Core.
Note
Use the profile which matches the Azure App registration Redirect URIs
Run the app.
dotnet run --launch-profile https
Browse to the app's secure endpoint, for example, https://localhost:5001/
.
Select the Privacy link.
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:
ASP.NET Core feedback
ASP.NET Core is an open source project. Select a link to provide feedback:
Events
Power BI DataViz World Championships
Feb 14, 4 PM - Mar 31, 4 PM
With 4 chances to enter, you could win a conference package and make it to the LIVE Grand Finale in Las Vegas
Learn moreTraining
Module
Secure a .NET web app with the ASP.NET Core Identity framework - Training
Learn how to add authentication and authorization to a .NET web app using the ASP.NET Core Identity framework.
Certification
Microsoft Certified: Identity and Access Administrator Associate - Certifications
Demonstrate the features of Microsoft Entra ID to modernize identity solutions, implement hybrid solutions, and implement identity governance.
Documentation
This article discusses using Azure Active Directory B2C to sign in and sign up users in an ASP.NET web application that calls a web API.
Enable authentication in a web API by using Azure AD B2C
Learn how to use Azure AD B2C to protect a web API. Enable authentication to authorize access to API endpoints with valid access tokens.
Enable web app authentication options using Azure Active Directory B2C
This article discusses several ways to enable web app authentication options.