c# - 对来自多个来源(例如 Cognito 和 Azure)的令牌进行身份验证
问题描述
我们正在开发一种 API,允许用户通过许多不同的提供商进行身份验证。单独的供应商不是问题,但将它们一起使用被证明是一个挑战。
似乎添加超过 1 个提供程序会InvalidOperationException
在应用程序启动时引发“方案已存在:承载”。
下面是ConfigureServices
来自的函数Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "Value";
options.Audience = "Value";
})
.AddMicrosoftIdentityWebApi(options =>
{
Configuration.Bind("AzureAdB2C", options);
options.TokenValidationParameters.NameClaimType = "name";
},
options => { Configuration.Bind("AzureAdB2C", options); });
services.AddControllers();
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder(
JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});
}
我使用 Microsoft 示例以 Azure AD作为起点进行身份验证。删除AddJwtBearer
orAddMicrosoftIdentityWebApi
调用工作正常,但我需要为我们的用例配置两个提供程序。
有没有办法用 .NET Core 3.1 或更高版本做到这一点?
解决方案
我们不能在相同的方案名称下注册 2 个身份验证。因此,我们需要注册 2 个具有不同名称的身份验证方案(或者一个具有默认名称,另一个具有方案名称)在我的情况下,我正在注册 2 个身份验证方案:
- 我自己的 JWT 方案,我们的应用名称为“MyAppName”,
- 使用 JWT 默认方案的 Azure AD 身份验证
JwtBearerDefaults.AuthenticationScheme
,因为我无法使用自定义方案名称添加它。
我能够使用以下配置使其工作:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer("MyAppName",options =>
{
options.Authority = "Value";
options.Audience = "Value";
})
.AddMicrosoftIdentityWebApi(Configuration, "AzureAd");
和授权配置:
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder(
"MyAppName",
JwtBearerDefaults.AuthenticationScheme)
.RequireAuthenticatedUser()
.Build();
});
推荐阅读
- string - Flutter:替换字符串中的换行符
- python - 如何修复 PYTHONPATHS 和 Python 的一个奇怪错误?
- javascript - FullCalander 5 添加事件
- html - 显示两个跨度元素,一个在另一个之下
- amazon-ec2 - 使用用户数据、云初始化指令和元数据的合适场景是什么
- python - 试图理解 numpy 数组负索引
- r - R:循环在 R 中创建新的数据帧
- javascript - 如何在文本之间插入 img?反应原生
- javascript - 我想拖动一个定义为数据属性的元素,我的问题是如何在这段代码中解决它:
- python - 图像搜索 Python 始终运行