我最近几天一直在研究ASP.NET Core的身份验证。我的应用程序有一个简单的身份验证令牌系统。请求中需要带有一个cookie,我会使用该cookie向我的身份验证服务器发送请求。身份验证服务器会返回用户的资格。如果cookie不存在或身份验证请求失败,则应用程序将返回401错误。成功后,它将进入管道的下一部分,并在资格上检查授权。
我设置了我的身份验证中间件,继承自AuthenticationHandler、AuthenticationMiddleware等。我的自定义身份验证处理程序继承自Authenticationhandler并覆盖HandleAuthenticateAsync()方法。此方法使用用户提供的cookie获取用户数据,创建我的ClaimsPrincipal,并返回AuthenticateResult.Success或AuthenticateResult.Fail。
当AuthenticationResult.Fail返回时,我认为应用程序会退出,但是我的应用程序仍将进入管道的下一部分(app.UseMvc()),而我认为它应该返回401错误。
我的Startup.cs如下所示。
我设置了我的身份验证中间件,继承自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));
});
这样设置是否正确?当身份验证失败时,管道不应该关闭吗?