.NET Core在AzuerAD身份验证后添加声明 [英] .NET Core add Claim after AzuerAD Authentication
问题描述
我的应用程序通过AzureAD登录,但是现在我需要从数据库获取信息,然后将角色存储为声明.
My application signs in via AzureAD, but now I need to get information from the DB and then store the Role as a Claim.
所以我的问题是:身份验证后如何将角色存储为Claim?
So my question is: How can I store the Role as Claim after authentication ?
这是我尝试过的:
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 ?
谢谢
推荐答案
您可以在身份验证期间实现这一点,在OIDC中间件中,OnTokenValidated
为您提供了修改从传入令牌获得的ClaimsIdentity的机会,以下代码用于您的参考:
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;
},
};
});
然后在controller中,您可以像这样获得索赔:
Then in controller , you can get the claim like :
var role = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;
这篇关于.NET Core在AzuerAD身份验证后添加声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!