.NET Core add Claim after AzuerAD Authentication

前端 未结 1 1795
猫巷女王i
猫巷女王i 2020-12-07 04:25

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 a

相关标签:
1条回答
  • 2020-12-07 05:03

    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;
    
    0 讨论(0)
提交回复
热议问题