Tom Crosman
Tom Crosman

Reputation: 1285

Adding Custom Claims to AspNetCore Azure Authenticated Application

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?

Upvotes: 1

Views: 1024

Answers (1)

Nan Yu
Nan Yu

Reputation: 27528

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;

Upvotes: 3

Related Questions