问题
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 , OnTokenValidated
offers 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