.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.
所以我的问题是:如何在身份验证后将角色存储为声明?
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;
},
};
});
然后在控制器中,您可以获得如下声明:
Then in controller , you can get the claim like :
var role = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;
这篇关于.NET Core 在 AzuerAD 身份验证后添加声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!