2016-10-06 142 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屬性。