When authentication using azure AzureADB2C I would like to add custom claims which are managed in the portal to the Claims Principle
current code in start u
In general, we would use OpenIdConnect middleware for AAD authentication. And you could use the following code lines for adding custom claim(s).
//OpenIdConnectOptions
options.Events = new OpenIdConnectEvents
{
OnTokenValidated = context =>
{
var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
//add your custom claims here
claimsIdentity.AddClaim(new Claim("test", "helloworld!!!"));
return Task.FromResult(0);
}
};
If you are using AzureADB2CAuthenticationBuilderExtensions.AddAzureADB2C by installing package Microsoft.AspNetCore.Authentication.AzureADB2C.UI, I assumed that there is no approach for you to set OpenIdConnectEvents.OnTokenValidated.
From AzureAdB2CAuthenticationBuilderExtensions.cs, you could find the code line under AddAzureADB2C
method for instantiating OpenIdConnectOptions
.
builder.Services.TryAddSingleton<IConfigureOptions<OpenIdConnectOptions>, OpenIdConnectOptionsConfiguration>();
For OpenIdConnectOptionsConfiguration.cs, you could find that you have no chance to set OpenIdConnectOptions.Events
.
Fortunately, here is a code sample which seperately defines AzureAdB2COptions.cs and OpenIdConnectOptionsSetup.cs. I assumed that you could follow my code snippet to modify the Configure
method under OpenIdConnectOptionsSetup.cs to meet your requirement. Detailed tutorial you could follow An ASP.NET Core web app with Azure AD B2C.