![](/img/trans.png)
[英]ASP.NET Core 2.0 custom middleware using cookie authentication
[英]ASP.NET Core 2.0 authentication middleware
隨着Core 1.1遵循@ blowdart的建議並實施了自定義中間件:
https://stackoverflow.com/a/31465227/29821
它的工作方式如下:
這有點適用於2.0,除了如果令牌無效(上面的步驟2)並且從未添加聲明我得到“沒有指定authenticationScheme,並且沒有找到DefaultChallengeScheme。”
所以現在我正在讀取2.0中的auth更改:
https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x
在ASP.NET Core 2.0中我做同樣的事情的正確途徑是什么? 我沒有看到做真正的自定義身份驗證的示例。
因此,經過漫長的一天嘗試解決這個問題后,我終於想出了微軟是如何讓我們為核心2.0中的新單一中間件設置制作自定義身份驗證處理程序的。
在查看MSDN上的一些文檔后,我找到了一個名為AuthenticationHandler<TOption>
的類,它實現了IAuthenticationHandler
接口。
從那里,我找到了一個完整的代碼庫,其中包含位於https://github.com/aspnet/Security的現有身份驗證方案
在其中一個內部,它顯示了Microsoft如何實現JwtBearer身份驗證方案。 ( https://github.com/aspnet/Security/tree/master/src/Microsoft.AspNetCore.Authentication.JwtBearer )
我將大部分代碼復制到一個新文件夾中,並清除了與JwtBearer
所有內容。
在JwtBearerHandler
類(擴展AuthenticationHandler<>
)中,有一個覆蓋Task<AuthenticateResult> HandleAuthenticateAsync()
我在舊的中間件中添加了通過自定義令牌服務器設置聲明,並且仍然遇到一些權限問題,當令牌無效且未設置聲明時,只吐出200 OK
而不是401 Unauthorized
。
我意識到我已經覆蓋了Task HandleChallengeAsync(AuthenticationProperties properties)
,無論出於何種原因,它都用於通過控制器中的[Authorize(Roles="")]
設置權限。
刪除此覆蓋后,代碼已經運行,並且在權限不匹配時已成功拋出401
。
最主要的一點是,現在您無法使用自定義中間件,您必須通過AuthenticationHandler<>
實現它,並且在使用services.AddAuthentication(...)
時必須設置DefaultAuthenticateScheme
和DefaultChallengeScheme
。
以下是這應該是什么樣子的一個例子:
在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 / Configure()中添加:
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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.