azure - 使用 AD 和 B2C 进行 ASP.Net Core 身份验证

标签 azure asp.net-core azure-active-directory azure-ad-b2c

我们有一个用 ASP.Net Core 2.2 编写的 Web api,我们希望根据 AAD 或 B2C 对用户进行身份验证。这意味着我们有一些端点只能由 AAD 用户访问,其他端点只能由 B2C 用户访问,还有一些端点两者都可以访问。

在 Startup.cs 中我们有

services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
   .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
   AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

这些单独工作,但是当我们尝试同时添加两者的配置时,两者都不起作用。

我也尝试过

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
   .AddAzureADBearer(options => Configuration.Bind("AzureAd", options))
   .AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));

但这似乎都不起作用。我们如何实现这一目标?

最佳答案

我也遇到了类似的问题并通过自定义策略实现。下面是验证码。

public static void AddAuthorization(this IServiceCollection services, IConfigurationRoot configuration)
    {
        services.AddAuthentication()
            .AddJwtBearer("AAD", options =>
            {
                options.MetadataAddress = configuration["AzureAd:Instance"] + configuration["AzureAd:TenantId"] +
                                          "/v2.0/.well-known/openid-configuration";
                options.Authority = configuration["AzureAd:Instance"] + configuration["AzureAd:TenantId"];
                options.Audience = configuration["AzureAd:ClientId"];
                options.TokenValidationParameters =
                    new TokenValidationParameters
                    {
                        ValidIssuer = $"https://sts.windows.net/{configuration["AzureAd:TenantId"]}/",
                    };
                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context => Task.CompletedTask,
                    OnChallenge = context => Task.CompletedTask,
                    OnAuthenticationFailed = (context) =>
                    {
                        Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                        return Task.CompletedTask;
                    },
                    OnTokenValidated = context =>
                    {
                        Console.WriteLine("Validated: " + context.SecurityToken);
                        return Task.CompletedTask;
                    }
                };
            })
            .AddJwtBearer("B2C", options =>
        {
            options.Authority = configuration["AzureAdB2C:Instance"] + configuration["AzureAdB2C:Domain"] + "/" + configuration["AzureAdB2C:SignUpSignInPolicyId"] + "/v2.0";
            options.Audience = configuration["AzureAdB2C:ClientId"];

            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context => Task.CompletedTask,
                OnChallenge = context => Task.CompletedTask,
                OnAuthenticationFailed = (context) =>
                {
                    Console.WriteLine("OnAuthenticationFailed: " + context.Exception.Message);
                    return Task.CompletedTask;
                },
                OnTokenValidated = context =>
                {
                    Console.WriteLine("Validated: " + context.SecurityToken);
                    return Task.CompletedTask;
                }
            };
        });
        services
            .AddAuthorization(options =>
            {
                options.AddPolicy("AADUsers", new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddAuthenticationSchemes("AAD")
                    .Build());

                options.AddPolicy("B2CUsers", new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .AddAuthenticationSchemes("B2C")
                    .Build());
            });
    }

在startup.cs中的ConfigureServices中添加以下代码

services.AddAuthorization(Configuration);

现在在你的 Controller 中你可以基于 AD 或 B2CAD 进行这样的装饰

[Authorize(Policy = "B2CUsers")] // For B2C authentication
[Authorize(Policy = "AADUsers")] // For AAD authentication

关于azure - 使用 AD 和 B2C 进行 ASP.Net Core 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55852498/

相关文章:

azure - 通过 ARM 模板在 Azure Web App 中为容器启用持续部署

c# - 如何将 IHttpContextAccessor 注入(inject) Autofac TenantIdentificationStrategy

c# - 如何在 ASP.NET Core 2.1 中的计时器上运行 BackgroundService

azure - 如何使用服务主体从第三方应用程序使用 SQLAlchemy 连接到 Azure Databricks 的 Hive?

azure - PowerBI、Azure AD 和 keycloak 身份验证。使用 keycloak 作为 Idps 登录 Power BI

azure - 当 Microsoft AD 图接近 EOF 时使用 Azure 资源管理器

android - 在 Android 上使用 Azure Speech to Text 拦截音频 blob 或将音频保存到文件

azure - 将数据写入 Dynamics 365 中的多重查找字段时,ADF 复制事件和数据流的行为不同

c# - 在 Azure AD B2C 中请求 token 时缺少范围 "scp"

asp.net-core - 用于点对点视频聊天的 ASP.NET Core 和 WebRTC