Custom AuthenticationHandler not working in Asp.Net Core 3

别来无恙 提交于 2020-01-25 00:26:11

问题


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();

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);
}

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 ?


回答1:


There's a problem with the order of your middleware

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

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

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

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



来源:https://stackoverflow.com/questions/58363002/custom-authenticationhandler-not-working-in-asp-net-core-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!