为什么Asp.Net核心认证方案是强制性的

我非常沮丧的是,在Asp.Net Core中,身份validation方案似乎是强制性的。 我的目标是构建一个API,我不想知道客户端的任何信息。 我已经建立了自定义身份validation和授权,工作正常。 我没有使用身份或cookie。 但是,如果没有有效的身份validation方案,我将无法返回403 Forbid结果,否则会出现以下exception…

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

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

在仔细阅读Asp.net Core安全源代码后,我设法创建了一个自定义身份validation处理程序。 为此,您需要实现3个类。

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

public class AwesomeAuthenticationOptions : AuthenticationOptions { public AwesomeAuthenticationOptions() { AuthenticationScheme = "AwesomeAuthentication"; AutomaticAuthenticate = false; } } 

第二个类实现了一个抽象的AuthenticationHandler。

 public class AwesomeAuthentication : AuthenticationHandler { protected override async Task 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 { public AwesomeAuthenticationMiddleware(RequestDelegate next, IOptions options, ILoggerFactory loggerFactory, UrlEncoder urlEncoder) : base(next, options, loggerFactory, urlEncoder) { } protected override AuthenticationHandler CreateHandler() { return new AwesomeAuthentication(); } } 

最后,使用Startup.cs Configure方法中的中间件组件。

 app.UseMiddleware(); 

现在,您可以构建自己的身份validation方案。