In this post let's see how we can configure Authentication in an ASP.NET Core Web API with Azure AD B2C and most importantly using explicit configuration.
The standard approach is something like below.
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(Configuration, "AzureAdB2C");
This I am highly against with, because we are picking up Configuration by the section named "AzureAdB2C" and it's not explicit. There are be many options that can be specified in section, and when we bound it like this, we don't know which are required and which are not.
So I personally always prefer being explicit over implicit.
public class AzureAdB2COptions
{
/// <summary>
/// Instance name: Ex: "https://{your-tenant-name}.b2clogin.com"
/// </summary>
/// <remarks>Required</remarks>
public string Instance { get; set; }
/// <summary>
/// Domain name: Ex: "{your-tenant-name}.onmicrosoft.com"
/// </summary>
/// <remarks>Required</remarks>
public string Domain { get; set; }
/// <summary>
/// Client Application Id
/// </summary>
/// <remarks>Required</remarks>
public string ClientId { get; set; }
/// <summary>
/// Your Azure AD B2C Application Policy Id
/// </summary>
/// <remarks>Required</remarks>
public string SignUpSignInPolicyId { get; set; }
}
And then, use the following overload.
AzureAdB2COptions azureAdB2COptions =
Configuration.GetSection("AzureAdB2C").Get<AzureAdB2COptions>();
services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(jwtBearerOptions =>
{
jwtBearerOptions.Audience = azureAdB2COptions.ClientId;
},
identityOptions =>
{
identityOptions.Instance = azureAdB2COptions.Instance;
identityOptions.Domain = azureAdB2COptions.Domain;
identityOptions.ClientId = azureAdB2COptions.ClientId;
identityOptions.SignUpSignInPolicyId = azureAdB2COptions.SignUpSignInPolicyId;
});
Hope this helps.
Happy Coding.
Regards,
Jaliya
No comments:
Post a Comment