0

I have a ASP.NET Core (.NET 6) API controller that makes sure that only authenticated users can access its endpoints using the Authorize attribute:

[ApiController]
[Authorize]
[Route("api/borrower")]
public class BorrowerController : ControllerBase
{
    ...
}

Since it serves a REST API, instead of returning 302 redirect responses, I prefer having 401 unautherized responses so I've configured my cookie authentication in Startup:

services.AddScoped<CookieAuthenticationEventsHandler>();
services.ConfigureApplicationCookie(o =>
{
    ...
    o.EventsType = typeof(CookieAuthenticationEventsHandler);
})

and:

public class CookieAuthenticationEventsHandler : CookieAuthenticationEvents
{
    public override Task RedirectToLogin(RedirectContext<CookieAuthenticationOptions> context)
    {
        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        return Task.FromResult(0);
    }
}

Works as expected. Instead of 302, I get a 401 on unauthenticated requests.

What does not work is when I introduce roles-based access control and I change the above [Authorize] to [Authorize(Roles = "Borrower")] for example.

A request to the controller with a principal that is authenticated but does not assume that role again results in a 302 instead of 401. Setting a breakpoint in the RedirectToLogin method shows that in this case the method is not being called (i.e. the event is not raised).

Also, I don't see any other event that would be suitable for this scenario.

Is this by design or is it a bug? Am I missing something here? And how could I still turn that 302 into a 401.

Dejan
  • 9,150
  • 8
  • 69
  • 117
  • Actually, it would be better to have a 403 Forbidden in the case of a missing role for an API end-point instead of a 302. – Dejan Feb 09 '22 at 13:41
  • Pls show your middleware order for me in Startup.cs. I want check `Authentication` and `Authorization` 's order. `Authentication` should always be placed before `Authorization`. – Jason Pan Feb 10 '22 at 09:28
  • @JasonPan I've check that and the order is fine. – Dejan Feb 10 '22 at 11:47
  • Your code about `services.AddScoped(); services.ConfigureApplicationCookie`, seems like registing as service, it will run when your application start. I suggest you create a middleware to handle this issue. https://stackoverflow.com/a/48646693/7687666 – Jason Pan Feb 11 '22 at 03:35

0 Answers0