在 MVC 核心应用程序中使用 AddAzureADB2C 时向 ClaimsPrincipal 添加自定义声明

chr*_*tle 2 c# azure claims azure-ad-b2c asp.net-core

使用 azure AzureADB2C 进行身份验证时,我想将门户中管理的自定义声明添加到声明原则

current code in start up 
   services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
                .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options));
Run Code Online (Sandbox Code Playgroud)

我认为它应该像这样工作,但在令牌验证时从未被击中

 services.AddAuthentication(AzureADB2CDefaults.AuthenticationScheme)
                .AddAzureADB2C(options => Configuration.Bind("AzureAdB2C", options))
                .AddJwtBearer(o =>
                    {
                        o.Events = new JwtBearerEvents
                                       {
                                           OnTokenValidated = async ctx =>
                                               {
                                                       var claims = new List<Claim> { new Claim("ConfidentialAccess", "true") };
                                                       var appIdentity = new ClaimsIdentity(claims);
                                                       ctx.Principal.AddIdentity(appIdentity);
                                               }
                                       };
                    });
Run Code Online (Sandbox Code Playgroud)

Bru*_*hen 8

通常,我们将使用 OpenIdConnect 中间件进行 AAD 身份验证。您可以使用以下代码行添加自定义声明。

//OpenIdConnectOptions
options.Events = new OpenIdConnectEvents
{
    OnTokenValidated = context =>
    {   
        var claimsIdentity = (ClaimsIdentity)context.Principal.Identity;
        //add your custom claims here
        claimsIdentity.AddClaim(new Claim("test", "helloworld!!!"));

        return Task.FromResult(0);
    }
};
Run Code Online (Sandbox Code Playgroud)

如果您通过安装包Microsoft.AspNetCore.Authentication.AzureADB2C.UI使用AzureADB2CAuthenticationBuilderExtensions.AddAzureADB2C,我认为您没有设置OpenIdConnectEvents.OnTokenValidated 的方法

AzureAdB2CAuthenticationBuilderExtensions.cs 中,您可以找到AddAzureADB2C用于实例化的方法下的代码行OpenIdConnectOptions

builder.Services.TryAddSingleton<IConfigureOptions<OpenIdConnectOptions>, OpenIdConnectOptionsConfiguration>();
Run Code Online (Sandbox Code Playgroud)

对于OpenIdConnectOptionsConfiguration.cs,您会发现您没有机会设置OpenIdConnectOptions.Events.

幸运的是,这里有一个代码示例,它分别定义了AzureAdB2COptions.csOpenIdConnectOptionsSetup.cs。我假设您可以按照我的代码片段修改OpenIdConnectOptionsSetup.csConfigure下的方法以满足您的要求。您可以遵循An ASP.NET Core web app with Azure AD B2C 的详细教程。