簡體   English   中英

自定義ASP.NET核心Cookie身份驗證

[英]Custom ASP.NET Core Cookie Authentication

我花了最近幾天在ASP.NET Core中為我的服務進行身份驗證。 我的應用有一個簡單的身份驗證令牌系統 預計請求上有cookie,我接受cookie並向我的auth服務器發出請求。 auth服務器返回用戶的權利。 如果cookie不存在,或者auth請求返回失敗,應用程序應該吐出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));
        });

這是應該如何設置的? 當身份驗證失敗時,管道是否應該關閉?

當身份驗證失敗時,管道是否應該關閉?

假設您有另一個身份驗證中間件:

    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屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM