为什么 Asp.Net Core 身份验证方案是强制性的

Nit*_*esh 5 c# security authentication asp.net-mvc asp.net-core

我对 Asp.Net Core 中似乎必须使用身份验证方案这一事实感到非常沮丧。我的目标是构建一个 API,我不想了解有关客户端的任何信息。我已经构建了自定义身份验证和授权,效果很好。我没有使用身份或 cookie。但是,如果没有有效的身份验证方案,我无法返回 403 Forbid 结果,否则我会收到以下异常...

System.InvalidOperationException:没有配置身份验证处理程序来处理方案:自动

我的问题是,我可以将 MVC 配置为不使用身份验证方案或创建身份验证方案而不依赖登录路径或任何路径吗?

Nit*_*esh 2

在仔细研究 Asp.net Core 安全源代码后,我成功创建了一个自定义身份验证处理程序。为此,您需要实现 3 个类。

第一个类实现一个抽象的 AuthenticationOptions。

public class AwesomeAuthenticationOptions : AuthenticationOptions {
    public AwesomeAuthenticationOptions() {
        AuthenticationScheme = "AwesomeAuthentication";
        AutomaticAuthenticate = false;
    }
}
Run Code Online (Sandbox Code Playgroud)

第二个类实现一个抽象的 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));
    }
}
Run Code Online (Sandbox Code Playgroud)

第三个类实现了一个抽象的 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,您在 Startup.cs 配置方法中使用中间件组件。

app.UseMiddleware<AwesomeAuthenticationMiddleware>();
Run Code Online (Sandbox Code Playgroud)

现在您可以构建自己的身份验证方案。