问题描述
我正在尝试创作一个网站,该网站使用 AzureAD 对用户进行身份验证以访问 UI 以创作数据库中的项目.而且我还希望其他服务可以通过不记名令牌调用此 API.
I'm trying to author a website that uses AzureAD to authenticate users to access UIs to author items in a DB. And I also want this API to be callable by other services via a bearer token.
services.AddAuthentication(o => {
o.DefaultScheme = AzureADDefaults.BearerAuthenticationScheme;
o.DefaultAuthenticateScheme = AzureADDefaults.AuthenticationScheme;
})
.AddAzureAD(options => Configuration.Bind("AzureAd", options))
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
我希望使用 AzureAD 方案对用户进行身份验证,但对同一 WEB API(在差异路由下)的服务由承载进行身份验证.或者拥有除两者之外的所有路线.两者都有效
I want users to be authenticated using the AzureAD scheme, but services to the same WEB API (under a dif route) to be authenticated by the bearer. Or have all routes except both. Either works
推荐答案
最终通过创建一个策略方案来解决这个问题,该方案根据存在的 auth 标头在两个模式之间切换:
ended up solving this by creating a policy scheme which toggles between the two schemas depending on the auth header present:
// add azure ad user and service authentication
services
.AddAuthentication("Azures")
.AddPolicyScheme("Azures", "Authorize AzureAd or AzureAdBearer", options =>
{
options.ForwardDefaultSelector = context =>
{
var authHeader = context.Request.Headers["Authorization"].FirstOrDefault();
if (authHeader?.StartsWith("Bearer") == true)
{
return AzureADDefaults.JwtBearerAuthenticationScheme;
}
return AzureADDefaults.AuthenticationScheme;
};
})
.AddAzureADBearer(options => config.Bind("AzureAdBearer", options))
.AddAzureAD(options => config.Bind("AzureAd", options));
这篇关于如何将 AzureAD 和 AzureADBearer 添加到 asp.net core 2.2 web api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!