我正在將使用 OWIN 和 .NET Framework 構建的自托管 Web API 移植到 ASP.NET Core Web API(使用 .NET 6.0)
在原始 API 中,我有一個自定義身份驗證機制,可以根據請求中的標頭動態地為每個呼叫選擇身份驗證方案:
HttpListener listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemeSelectorDelegate = new AuthenticationSchemeSelector((httpRequest) =>
{
if(httpRequest.Headers.AllKeys.Any(k => k == "MyCustomHeader"))
{
return AuthenticationSchemes.Ntlm;
}
else
{
return AuthenticationSchemes.Anonymous;
}
});
基本上,對于每個請求,我都會檢查請求中的特定標頭,并根據該標頭選擇是強制請求使用 Windows 身份驗證還是允許匿名處理請求。
如何在 ASP.net Core web api 中復制此行為?我通過使用Microsoft.AspNetCore.Authentication.NegotiateNuGet 包和配置了解了如何使用 Windows 身份驗證:
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();
但是,我不知道如何像以前一樣根據標頭動態選擇是使用該方案還是允許匿名呼叫。
這可能嗎?我該怎么做?
uj5u.com熱心網友回復:
這是一種方法
services.AddAuthentication(opts =>
{
opts.DefaultScheme = "DynamicAuthenticationScheme";
})
.AddScheme<SystemSessionAuthenticationRelatedOptions, SystemAuthenticationRelatedHandler>(
CommonConstants.SessionAuthentication, x => x.Test = "Ran in here")
.AddCookie("CookieScheme")
.AddJwtBearer(options =>
{
options.Authority = identityUrl;
options.Audience = "shipping";
options.RequireHttpsMetadata = false;
})
.AddPolicyScheme("DynamicAuthenticationScheme", "Default system policy",
cfgOpts => cfgOpts.ForwardDefaultSelector = ctx =>
ctx.Request.Headers.ContainsKey("IsTheSecretHeaderPresent?")
? "CookieScheme"
: JwtBearerDefaults.AuthenticationScheme);
我們的想法是為 指定一個默認的身份驗證方案 DynamicAuthenticationScheme,我們相應地為 Cookie 和 Jwt 身份驗證添加了另外兩個名為CookieScheme和JwtBearerDefaults.AuthenticationScheme常量的身份驗證方案。
然后將我們的默認身份驗證方案定義為基于標頭資訊的身份驗證機制的路由。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371330.html
標籤:C# asp.net核心 拥有 窗口认证 asp.net-core-authenticationhandler
上一篇:Razor頁面獲取屬性查詢命名
