1

I am using the AspNetCore template authorization with this line of code:

       services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));

How can I add my custom Claims after the user is authorized by Azure?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Tom Crosman
  • 1,137
  • 1
  • 12
  • 37

1 Answers1

3

You can add custom cliams in OnTokenValidated of OIDC event :

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
            .AddAzureAD(options => Configuration.Bind("AzureAd", options));


services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = ctx =>
        {


            // add claims
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Role, "Admin")
            };
            var appIdentity = new ClaimsIdentity(claims);

            ctx.Principal.AddIdentity(appIdentity);

            return Task.CompletedTask;
        },
    };
});

Then in controller , you can get the claim like :

var role = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;
Nan Yu
  • 26,101
  • 9
  • 68
  • 148