c# - 在 MVC Core 应用程序中使用 AddAzureADB2C 时向 ClaimsPrincipal 添加自定义声明

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

使用 azure 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);
                                               }
                                       };
                    });

最佳答案

一般情况下,我们会使用 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);
    }
};

如果您使用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 方法。以满足您的要求。详细教程可以关注An ASP.NET Core web app with Azure AD B2C .

关于c# - 在 MVC Core 应用程序中使用 AddAzureADB2C 时向 ClaimsPrincipal 添加自定义声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51965665/

相关文章:

c# - 使用 GetSchema 检索表的列

C# P/Invoke void** 指针传递

c# - 已经用相同的参数类型定义了一个名为 'InitializeComponent' 的成员

c# - 无法使用 c# .net 连接 Azure MySQL

azure - 具有 Azure AD 访问权限的 Terraform Azure Linux VM

jquery - 通过 jQuery.html() 传递时 ASP 页面链接不可用

C# for Windows Phone 7,为什么使用这种语言

azure - 在 Visual Studio Team Services 中部署后运行集成测试

c# - 如何使用 Web API Get 方法返回图像

c# - 在 .Net Core 中获取文件扩展属性