Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core add Claim after AzuerAD Authentication

My application signs in via AzureAD, but now I need to get information from the DB and then store the Role as a Claim.

So my question is: How can I store the Role as Claim after authentication ?

This is what I tried:

var user = User as ClaimsPrincipal;
var identity = user.Identity as ClaimsIdentity;
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));  

But when I go to another controller, the claim does not exist anymore ?

Thanks

like image 856
bbrinck Avatar asked Nov 15 '25 21:11

bbrinck


1 Answers

You can achieve that during the authentication , in OIDC middleware , OnTokenValidatedoffers you the chance to modify the ClaimsIdentity obtained from the incoming token , code below is for your reference :

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


services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Events = new OpenIdConnectEvents
    {
        OnTokenValidated = ctx =>
        {
            //query the database to get the role

            // 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;
like image 83
Nan Yu Avatar answered Nov 17 '25 11:11

Nan Yu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!