【发布时间】:2017-02-15 15:37:49
【问题描述】:
过去几天我一直在研究 ASP.NET Core 中我的服务的身份验证。我的应用程序有一个简单的身份验证令牌系统。预计该请求上有一个 cookie,我获取该 cookie 并向我的身份验证服务器发出请求。身份验证服务器将用户的权利归还给我。如果 cookie 不存在,或者身份验证请求返回失败,则应用应输出 401。如果成功,它将转到管道的下一部分并检查权利的授权。
我按照预期设置了我的身份验证中间件 - 从 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));
});
这是应该如何设置的吗?身份验证失败时,管道不应该关闭吗?
【问题讨论】:
标签: asp.net .net asp.net-web-api asp.net-core .net-core