自定义ASP.NET Core Cookie身份验证

3
我最近几天一直在研究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));
        });

这样设置是否正确?当身份验证失败时,管道不应该关闭吗?

1个回答

3
当身份验证失败时,管道不应该关闭吗?
假设您有另一个身份验证中间件:
    app.UseCustomAuthentication(new CustomAuthenticationOptions()
    {
        AutomaticChallenge = true,
        AutomaticAuthenticate = true
    });
    app.UseOtherAuthentication(new OtherAuthenticationOptions()
    {
        AutomaticChallenge = true,
        AutomaticAuthenticate = true
    });

如果管道在第一次身份验证失败时结束,其他身份验证中间件将永远不会运行。这将使其可扩展性更低。
另外,假设您想使用AllowAnonymous属性允许一些匿名请求进行某些操作。您该如何允许?
即使身份验证中间件失败,服务器也不会响应401、403或302,除非调用HttpContext.Authentication.ChallengeAsync()或使用Authorize属性。
据我所知,这是预期的行为,内置的cookie身份验证也具有相同的行为。如果您想要首先强制进行身份验证,您需要全局添加它(就像您所做的那样)或在控制器顶部使用Authorize属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接