自定义ASP.NET核心Cookie身份验证

时间:2016-10-06 18:55:09

标签: asp.net .net asp.net-web-api asp.net-core .net-core

我花了最近几天在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错误。

My 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 个答案:

答案 0 :(得分:3)

  

当身份验证失败时,管道是否应该关闭?

假设您有另一个身份验证中间件:

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