目前,我们的ASP有一个可用的OAuth身份验证。NET核心5 Web API。我们还想添加一个证书身份验证,以双重确定我们的呼叫者。有办法同时拥有它们吗?我尝试了下面的代码,但它覆盖了其中一个。
services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
.AddAzureADBearer(options =>
{
options.Instance = aADInstance;
options.ClientId = clientIdWithScope;
options.Domain = aADDomain;
options.TenantId = aADTenantId;
}
)
services.AddAuthentication(
CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate();
更改默认策略
// Add authentication schemes before, we already did this, so I would skip this part
// Change default Authorization policy
services.AddAuthorization(cfg =>
cfg.DefaultPolicy =
new AuthorizationPolicyBuilder(CertificateAuthenticationDefaults.AuthenticationScheme,
AzureADDefaults.JwtBearerAuthenticationScheme).RequireAuthenticatedUser().Build());
[Authorize]
属性现在需要所有http请求同时满足CertificateAuthenticationDefaults.AuthenticationScheme
和AzureADDefaults.JwtBearerAuthenticationScheme
,这可能不是我们想要的所有端点的行为,所以要小心这种方法。
添加我们自己的策略
// Add authentication schemes before, we already did this, so I would skip this part
// Adding our own policy
services.AddAuthorization(options =>
{
options.AddPolicy("ComposedPolicy", p =>
{
p.AuthenticationSchemes = new List<string>
{CertificateAuthenticationDefaults.AuthenticationScheme, AzureADDefaults.JwtBearerAuthenticationScheme};
p.RequireAuthenticatedUser();
p.Build();
});
});
[Authorize]
属性行为现在将是不受欢迎的,但无论何时我们想要使用自定义策略,我们都必须通过[Authorize(Policy = "ComposedPolicy")]
指定它们。
只需选择最适合的方法