在仔细研究了 Asp.net Core 安全源代码之后,我设法创建了一个自定义身份验证处理程序。为此,您需要实现 3 个类。
第一个类实现了一个抽象的 AuthenticationOptions。
public class AwesomeAuthenticationOptions : AuthenticationOptions {
public AwesomeAuthenticationOptions() {
AuthenticationScheme = "AwesomeAuthentication";
AutomaticAuthenticate = false;
}
}
第二个类实现了一个抽象的AuthenticationHandler。
public class AwesomeAuthentication : AuthenticationHandler<AwesomeAuthenticationOptions>
{
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var prop = new AuthenticationProperties();
var ticket = new AuthenticationTicket(Context.User, prop, "AwesomeAuthentication");
//this is where you setup the ClaimsPrincipal
//if auth fails, return AuthenticateResult.Fail("reason for failure");
return await Task.Run(() => AuthenticateResult.Success(ticket));
}
}
第三个类实现了一个抽象的AuthenticationMiddleware。
public class AwesomeAuthenticationMiddleware : AuthenticationMiddleware<AwesomeAuthenticationOptions>
{
public AwesomeAuthenticationMiddleware(RequestDelegate next,
IOptions<AwesomeAuthenticationOptions> options,
ILoggerFactory loggerFactory,
UrlEncoder urlEncoder) : base(next, options, loggerFactory, urlEncoder) {
}
protected override AuthenticationHandler<AwesomeAuthenticationOptions> CreateHandler()
{
return new AwesomeAuthentication();
}
}
最后,在 Startup.cs 的 Configure 方法中使用中间件组件。
app.UseMiddleware<AwesomeAuthenticationMiddleware>();
现在您可以构建自己的身份验证方案。