在使用AddAzureADB2C创建MVC Core应用程序时,向ClaimsPrincipal添加自定义声明

3

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

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

我认为它应该像这样工作,但仅在Token验证通过时才有效。
 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);
                                               }
                                       };
                    });
1个回答

11

一般来说,我们会使用OpenIdConnect中间件进行AAD身份验证。您可以使用以下代码行添加自定义声明(s)。

//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);
    }
};
如果你正在使用 AzureADB2CAuthenticationBuilderExtensions.AddAzureADB2C 并安装了 Microsoft.AspNetCore.Authentication.AzureADB2C.UI 包,我假设你无法设置 OpenIdConnectEvents.OnTokenValidated
AzureAdB2CAuthenticationBuilderExtensions.cs 中,你可以找到在 AddAzureADB2C 方法下实例化 OpenIdConnectOptions 的代码行。
builder.Services.TryAddSingleton<IConfigureOptions<OpenIdConnectOptions>, OpenIdConnectOptionsConfiguration>();

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

幸运的是,这里有一个代码示例,分别定义了AzureAdB2COptions.csOpenIdConnectOptionsSetup.cs。我假设您可以按照我的代码片段修改OpenIdConnectOptionsSetup.cs下的Configure方法以满足您的要求。详细的教程可以参考使用 Azure AD B2C 的 ASP.NET Core Web 应用程序


在您的代码中,您复制了 context.Principal.Identity,然后仅向该 var claimsIdentity 副本添加声明。我不明白为什么 context.Principal.Identity 最终也包含自定义声明? - Lukas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接