【问题标题】:Adding custom claims to ClaimsPrincipal when using AddAzureADB2C in MVC Core App在 MVC Core App 中使用 AddAzureADB2C 时向 ClaimsPrincipal 添加自定义声明
【发布时间】:2019-01-28 15:28:19
【问题描述】:

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

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

我在想它应该像这样工作,但令牌验证永远不会被击中

 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);
                                               }
                                       };
                    });

【问题讨论】:

    标签: c# azure asp.net-core azure-ad-b2c claims


    【解决方案1】:

    一般来说,我们会使用 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);
        }
    };
    

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

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

    builder.Services.TryAddSingleton<IConfigureOptions<OpenIdConnectOptions>, OpenIdConnectOptionsConfiguration>();
    

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

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

    【讨论】:

    • 在您的代码中复制context.Principal.Identity,然后仅将声明添加到该var claimsIdentity 副本。我不明白为什么 context.Principal.Identity 最终也包含自定义声明?
    猜你喜欢
    • 2018-05-13
    • 2018-05-20
    • 1970-01-01
    • 2021-07-20
    • 2016-11-14
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多