Adding custom claims to ClaimsPrincipal when using AddAzureADB2C in MVC Core App

前端 未结 1 1445
无人及你
无人及你 2020-12-18 14:34

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         


        
相关标签:
1条回答
  • 2020-12-18 15:39

    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.

    0 讨论(0)
提交回复
热议问题