我已经花了最近几天在ASP.NET Core中使用身份验证来处理我的服务。我的应用有一个简单的身份验证令牌系统预计请求上有一个cookie,我将该cookie发送给我的auth服务器。 auth服务器让我回到用户的权利。如果cookie不存在,或者auth请求返回失败,那么应用程序应该吐出一个401.一旦成功,它将进入管道的下一部分并检查授权的授权。定制ASP.NET核心Cookie身份验证
我设置了我的认证中间件,就像我们期望的那样 - 从AuthenticationHandler,AuthenticationMiddleware等继承。我的自定义认证处理程序继承自Authenticationhandler并覆盖HandleAuthenticateAsync()。此方法使用用户提供的cookie来获取用户数据,创建我的ClaimsPrincipal并返回AuthenticateResult.Success或AuthenticateResult.Fail。
当AuthenticationResult.Fail返回时,我想应用程序将退出,但我的应用程序仍然会去管道的下一部分(app.UseMvc()),当时我认为它会返回401错误。
我的Startup.cs如下所示。
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCustomAuthentication(new CustomAuthenticationOptions()
{
AutomaticChallenge = true,
AutomaticAuthenticate = true
});
app.UseMvc();
}
}
这将失败身份验证,我会在输出中看到它,但UseMvc仍然会运行。直到我这样做了服务,它会退出,但有一个授权错误,而不是应该被标记的身份验证错误。
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});
这是它应该如何设置?当认证失败时,不应该关闭管道吗?