.NET Core add Claim after AzuerAD Authentication

我们两清 提交于 2020-01-16 08:40:16

问题


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


回答1:


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;


来源:https://stackoverflow.com/questions/59564952/net-core-add-claim-after-azuerad-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!