2016-10-06 140 views
1

我已经花了最近几天在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)); 
     }); 

这是它应该如何设置?当认证失败时,不应该关闭管道吗?

回答

2

当认证失败时,管道是否不应该关闭?

假设你有另外的认证中间件:

app.UseCustomAuthentication(new CustomAuthenticationOptions() 
    { 
     AutomaticChallenge = true, 
     AutomaticAuthenticate = true 
    }); 
    app.UseOtherAuthentication(new OtherAuthenticationOptions() 
    { 
     AutomaticChallenge = true, 
     AutomaticAuthenticate = true 
    }); 

如果在第一次验证失败管道结束,其他的认证中间件从来不运行。这将不太可扩展。

另一点,假设您希望允许使用AllowAnonymous属性的匿名请求的某些操作。你如何允许?

即使验证失败的中间件,而不调用HttpContext.Authentication.ChallengeAsync()或使用Authorize属性,服务器没有响应,401,403或302

据我知道这是预期的行为,并内置cookie认证工作同样的行为。如果您想首先强制通过身份验证的用户,则需要将其全局添加(如同您所做的那样),或者在控制器上使用Authorize属性。