.NET Core 在 AzuerAD 身份验证后添加声明

bbr*_*nck 4 .net claims-based-identity .net-core asp.net-core microsoft-identity-platform

我的应用程序通过 AzureAD 登录,但现在我需要从数据库获取信息,然后将角色存储为声明。

所以我的问题是:身份验证后如何将角色存储为声明?

这是我尝试过的:

var user = User as ClaimsPrincipal;
var identity = user.Identity as ClaimsIdentity;
identity.AddClaim(new Claim(ClaimTypes.Role, "Admin"));  
Run Code Online (Sandbox Code Playgroud)

但是当我转到另一个控制器时,该声明不再存在?

谢谢

Nan*_* Yu 7

您可以在身份验证期间实现这一点,在 OIDC 中间件中,OnTokenValidated您可以修改从传入令牌获取的 ClaimsIdentity,以下代码供您参考:

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;
        },
    };
});
Run Code Online (Sandbox Code Playgroud)

然后在控制器中,您可以获得如下声明:

var role = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value;
Run Code Online (Sandbox Code Playgroud)

  • @bbrinck,尝试:`var db = ctx.HttpContext.RequestServices.GetRequiredService&lt;YourDbContext&gt;();` (2认同)