Overriden HandleUnauthorizedAsync不被称为.NET Core

时间:2017-05-16 20:01:29

标签: .net asp.net-core unauthorized custom-authentication

我已经实现了自己的自定义身份验证中间件和处理程序,并在应用启动时配置了它们。这一切都很好。

在我的自定义身份验证处理程序中,我已经覆盖HandleAuthenticateAsync()以执行我自己的自定义身份验证,我还覆盖了HandleUnauthorizedAsync()以便将用户重定向到登录页面,但这不会被调用。

浏览器在响应中收到401(未授权)。我期待调用我的HandleUnauthorizedAsync()。

我在这里没有正确理解管道吗?

由于

4 个答案:

答案 0 :(得分:8)

在我的情况下,

user1859022有所帮助,但是我不想为每个-replace键入方案的名称。首先,指定[Authorize]也不起作用。

我的错误有点愚蠢。我同时拥有DefaultAuthenticateSchemeapp.UseAuthorization(),当然顺序是错误的。正确的版本是

app.UseAuthentication()

因此,请确保先将public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapControllers()); } 称为 UseAuthentication

答案 1 :(得分:5)

在我的情况下,我的处理程序未被调用的原因是我的AuthenticationScheme未被选为默认值。 我必须将它包含在Authorize属性中,如下所示:

[HttpGet]
[Authorize(AuthenticationSchemes= "MyAuth")]
public IEnumerable<string> Get()
{
    ...
}

btw:AutomaticChallenge

中似乎已删除了.net core 2.0选项

答案 2 :(得分:3)

上面的解决方案确实对我有用,我可以使用以下代码段对其进行改进,然后无需在Authorize属性中指定身份验证方案名称。在AddMvc之前调用AddAuthentication方法很重要。

public void ConfigureServices(IServiceCollection services)
{
    //must be placed before the AddMvc call
    services.AddAuthentication(options => 
                {                    
                    options.DefaultAuthenticateScheme = "MyAuth";
                    options.DefaultChallengeScheme = "MyAuth";
                })
                .AddCustomAuth(o => { });

    services.AddMvc();
}

答案 3 :(得分:1)

米哈伊尔的回答为我解决了这个问题,但只是为了清楚:

如果您的请求命中 ChallengeAsync 但未命中 HandleAuthenticateAsyncAuthenticateAsync

然后检查您的订单:

  1. app.UseAuthentication();
  2. app.UseAuthorization();
相关问题