問題描述
我正在嘗試創(chuàng)作一個(gè)網(wǎng)站,該網(wǎng)站使用 AzureAD 對(duì)用戶進(jìn)行身份驗(yàn)證以訪問 UI 以創(chuàng)作數(shù)據(jù)庫中的項(xiàng)目.而且我還希望其他服務(wù)可以通過不記名令牌調(diào)用此 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 方案對(duì)用戶進(jìn)行身份驗(yàn)證,但對(duì)同一 WEB API(在差異路由下)的服務(wù)由承載進(jìn)行身份驗(yàn)證.或者擁有除兩者之外的所有路線.兩者都有效
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
推薦答案
最終通過創(chuàng)建一個(gè)策略方案來解決這個(gè)問題,該方案根據(jù)存在的 auth 標(biāo)頭在兩個(gè)模式之間切換:
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));
這篇關(guān)于如何將 AzureAD 和 AzureADBearer 添加到 asp.net core 2.2 web api的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!