自定义AuthenticationHandler在Asp.Net Core 3中不起作用 [英] Custom AuthenticationHandler not working in Asp.Net Core 3

查看:397
本文介绍了自定义AuthenticationHandler在Asp.Net Core 3中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定在Asp.Net Core 2.2中是否会发生同样的情况,但是当我升级到最新的Asp.net Core 3版本时,这种情况正在发生.所以,我的问题是我创建了一个自定义AuthenticationHandler,如下所示:

I am not sure if the same happens in Asp.Net core 2.2 but this is happening when I upgraded to the latest Asp.net Core 3 version. So, my issue is that I have created a custom AuthenticationHandler like below:

public class PlatformAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public PlatformAuthenticationHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options, 
        ILoggerFactory logger, 
        UrlEncoder encoder,
        ISystemClock clock) 
        : base(options, logger, encoder, clock)
    {
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var sessionTokenStr = Request.Headers[Headers.SessionToken];
        var userTokenStr = Request.Headers[Headers.UserToken];

        if (string.IsNullOrEmpty(sessionTokenStr) ||
            Guid.TryParse(sessionTokenStr, out var sessionToken))
        {
            return AuthenticateResult.Fail("Session token should be present and in GUID format");
        }

        if (string.IsNullOrEmpty(userTokenStr) ||
            Guid.TryParse(userTokenStr, out var userToken))
        { 
            return AuthenticateResult.Fail("User token should be present and in GUID format");
        }
        //... and so on...
    }
}

在我的启动课程中,我注册如下身份验证:

In my startup class I register authentication like below:

collection.AddAuthentication(PlatformScheme.HeaderScheme)
.AddScheme<AuthenticationSchemeOptions, PlatformAuthenticationHandler>(PlatformScheme.HeaderScheme, null);
collection.AddAuthorization();

以及在Configure方法中:

and also in Configure method:

public void Configure(
    IApplicationBuilder app)
{
    app.UseDeveloperExceptionPage();
    app.UseMiddleware<ErrorHandlerMiddleware>();
    app.UseCors();
    //app.UseMiddleware<SessionBuilderMiddleware>();
    app.UseCoreFoundation();//custom library
    app.UseStaticFiles();
    app.UseStatusCodePages();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/PlatformApi/swagger.json", "Platform Api");
        c.RoutePrefix = "";
    });
}

我有一个简单的操作,如下所示:

I have a simple action like below:

[HttpGet(UrlPath + "claims")]
[Authorize]
public Task<IDictionary<string, object>> GetClaims(bool refresh)
{
    return _authenticationProvider.GetClaimsAsync(refresh);
}

在调试时,我可以看到我返回了AuthenticateResult.Fail("Session token should be present and in GUID format");,下一步,它进入了GetClaims方法中.为什么会发生这种情况? -如果我从处理程序返回失败,那不应该阻止我以后再访问该方法吗?

While debugging I can see I return AuthenticateResult.Fail("Session token should be present and in GUID format"); and as a next step it goes inside GetClaims method. Why does this happen ? - If I return failure from handler, isn't that supposed to stop me from accessing the method afterwards ?

推荐答案

中间件的顺序有问题

app.UseRouting();
app.UseCors();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints => {
   endpoints.MapControllers();
});

UseAuthentication()UseAuthorization()应该放在UseRouting()之后和UseEndpoints()之前,如

UseAuthentication() and UseAuthorization() should be placed after UseRouting() and before UseEndpoints() as this is described in the docs.

这篇关于自定义AuthenticationHandler在Asp.Net Core 3中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆