我们正在开发一个 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();
});
}
我正在使用微软的例子用于使用 Azure AD 进行身份验证作为起点。删除任一AddJwtBearer
or AddMicrosoftIdentityWebApi
调用工作正常,但我需要为我们的用例配置两个提供程序。
有没有办法在 .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();
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)