Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net Core custom authorization always ends with 401 Unauthorized

I am trying to implement a custom Authentication/Authorization flow with asp.net core but fails to do so. The authentication seems to work ok: if I debug step by step I can see that an AuthenticationTicket is created from a ClaimsPrincipal that contains an identity with isAuthenticated to true:

public class MyAuthHandler : AuthenticationHandler<MyAuthOptions>
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // grab stuff from the HttpContext
        string authHeader = Request.Headers["Authorization"];
        // do some stuff that are successfull in my tests
        var cp = DoTokenBasedAuthentication(authHeader);

        var ticket = new AuthenticationTicket(cp,
            new AuthenticationProperties(), Options.AuthenticationScheme);
        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

However, I try to add a dummy AuthorizationHandler after that:

public class MyRequirement : IAuthorizationRequirement
{
    public MyRequirement()
    {
    }
}

public class MyAuthRequirement : AuthorizationHandler<MyRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
    {
        context.Succeed(requirement);
        return Task.CompletedTask;
    }
}

And with this code in my startup file:

services.AddAuthorization(options =>
{
   options.AddPolicy("My",
      policy => policy.Requirements.Add(new MyRequirement()));
});

But whenever I add "[Authorize("My")]" on a controller, then all calls always returns 401. And my AuthorizationHandler is never reached. This problem looks similar to Asp.Net Core policy based authorization ends with 401 Unauthorized but is slightly different as on my case I have a user that is authenticated. I am struggling to debug into asp.net MVC source code, so I do not really know what is going on.

like image 354
CanardMoussant Avatar asked Jan 04 '23 15:01

CanardMoussant


1 Answers

Your authorization handler doesn't appear to be plugged in. You can try to add the following line to your Startup.ConfigureServices method :

services.AddSingleton<IAuthorizationHandler, MyAuthRequirement>();
like image 122
Métoule Avatar answered May 31 '23 21:05

Métoule