問題描述
我正在嘗試創作一個網站,該網站使用 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的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!