因此,試圖解決這個問題,經過漫長的一天,我終於想通了,微軟希望我們如何讓自定義驗證處理程序在覈心2.0新單曲的中間件的設置。
通過一些MSDN上的文檔尋找後,我發現了一個名爲AuthenticationHandler<TOption>
類,它實現了IAuthenticationHandler
接口。
從那裏,我發現了位於https://github.com/aspnet/Security
裏面的其中之一的現有認證方案的整個代碼庫,它顯示了微軟是如何實現JwtBearer認證方案。 (https://github.com/aspnet/Security/tree/dev/src/Microsoft.AspNetCore.Authentication.JwtBearer)
我將大部分代碼複製到一個新文件夾中,並清除了所有與JwtBearer
有關的事情。
在JwtBearerHandler
類(擴展AuthenticationHandler<>
),有一個爲Task<AuthenticateResult> HandleAuthenticateAsync()
我在我們的舊中間件添加了對通過自定義令牌服務器設置要求的覆蓋,並且仍然遇到一些問題的權限,只是隨地吐痰如果令牌無效並且沒有設置索賠,則輸出200 OK
而不是401 Unauthorized
。
我意識到我已經重寫了Task HandleChallengeAsync(AuthenticationProperties properties)
,無論什麼原因,它都是通過控制器中的[Authorize(Roles="")]
來設置權限。
刪除此重寫後,代碼已經工作,並且在權限不匹配時已成功拋出401
。
從這個主要的外賣是,現在你不能使用自定義的中間件,你必須通過AuthenticationHandler<>
實現它,你有DefaultAuthenticateScheme
和DefaultChallengeScheme
使用services.AddAuthentication(...)
時設置。
下面的這是什麼都應該看起來像一個例子:
在Startup.cs/ConfigureServices()地址:
services.AddAuthentication(options =>
{
// the scheme name has to match the value we're going to use in AuthenticationBuilder.AddScheme(...)
options.DefaultAuthenticateScheme = "Custom Scheme";
options.DefaultChallengeScheme = "Custom Scheme";
})
.AddCustomAuth(o => { });
在Startup.cs /配置()地址:
app.UseAuthentication();
創建一個新文件CustomAuthExtensions.cs
public static class CustomAuthExtensions
{
public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder, Action<CustomAuthOptions> configureOptions)
{
return builder.AddScheme<CustomAuthOptions, CustomAuthHandler>("Custom Scheme", "Custom Auth", configureOptions);
}
}
創建一個新的文件CustomAuthOptions.cs
public class CustomAuthOptions: AuthenticationSchemeOptions
{
public CustomAuthOptions()
{
}
}
創建一個新的文件CustomAuthHandler.cs
internal class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
public CustomAuthHandler(IOptionsMonitor<CustomAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
{
// store custom services here...
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
// build the claims and put them in "Context"; you need to import the Microsoft.AspNetCore.Authentication package
return AuthenticateResult.NoResult();
}
}
試試這個鏈接,即使它說,2種方案,但它將給ü上的身份驗證HTTPS對決://wildermuth.com/2017/08/19/Two-AuthorizationSchemes-in-ASP-NET-Core-2 –
您可以添加您的代碼,以便我們可以看看嗎?我知道我在core2.0的智威湯遜有問題 - 是在啓動時移動它的一個案例 – Webezine