對於ASP.NET Core 2.0,有些事情已經改變,您也可以使用AuthenticationHandler。
幫助您入門的好文檔是https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x。
我用我的當前項目自定義身份驗證的一個例子:
Startup.ConfigureServices:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = "Custom Scheme";
options.DefaultChallengeScheme = "Custom Scheme";
}).AddCustomAuth(o => { });
Startup.Configure:
app.UseAuthentication();
最後:
internal class CustomAuthenticationHandler :
AuthenticationHandler<CustomAuthenticationOptions>
{
public CustomAuthenticationHandler(IOptionsMonitor<CustomAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) :
base(options, logger, encoder, clock)
{
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
try
{
// Your auth code here
// Followed by something like this:
return AuthenticateResult.Success(
new AuthenticationTicket(
new ClaimsPrincipal(
new ClaimsIdentity(
new List<Claim>() { new Claim(ClaimTypes.Sid, Id.ToString()) },
Scheme.Name)),
Scheme.Name));
}
catch
{
return AuthenticateResult.Fail("Error message.");
}
}
}
這樣,所有對您的控制器的調用都將通過身份驗證中間件,並且您可以通過在控制器上使用[AllowAnonymous]
屬性(如有必要)忽略它。
https://damienbod.com/2015/09/15/asp-net-5-action-filters/ – Hackerman
它們是什麼樣的標記?有很多現有的基礎設施來做到這一點。以JwtBearer爲例。 – Tratcher
我現在只需在一個地方閱讀和驗證標題。但是,我會讀到JwtBearer要知道,thx。 –