Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequireAuthorization() on endpoints.MapControllerRoute() not working and every request passes through

I have the following code in an Asp.Net Core 3.1

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseRouting();

    app.UseCors(DefaultCorsPolicyName);

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

    app.UseEndpoints(endpoints =>
    {
    endpoints.MapControllerRoute("default", "{controller}/{action}/{id?}").RequireAuthorization(new AuthorizeAttribute());
    });
}


[ApiController]
[Route("[controller]/[action]")]
public class TestController : ControllerBase
{
    [HttpGet]
    public string Test()
    {
        return "Test works!";
    }
}

but all requests pass through and no authorization works. Any idea why this happens?

like image 314
pantonis Avatar asked Mar 02 '23 17:03

pantonis


2 Answers

Add endpoints.MapControllers().RequireAuthorization(...); into your endpoint configuration.

Your controller have own/explicit Route attribute and is not covered by MapControllerRoute call.

like image 61
Dmitry Avatar answered Mar 05 '23 17:03

Dmitry


Got bitten by this as well, I had a code like this:

services.AddAuthorization(options =>
  {
     options.DefaultPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddRequirements(new MustBeSuperAdminRequirement())
        .Build();
  })

One would be forgiven to think that MustBeSuperAdminRequirement won't be called if user has not logged in... but it is not so!... it went straight in and I spent a few hours scratching my head...

As a workaround I did this:

public static IMvcBuilder ConfigureMvc(this IServiceCollection services)
{
  services
    .AddAuthorization(options =>
     {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
        //.RequireAuthenticatedUser()  //<-- this does not seems to do anything, refer: https://github.com/dotnet/aspnetcore/issues/4656#issuecomment-605012014
        .AddRequirements(new MustBePtwUserRequirement())
        .Build();
     })
protected override async Task HandleRequirementAsync(
            AuthorizationHandlerContext context,
            MustBeSuperAdminRequirement requirement)
{
    var principal = context.User;
    if (!principal.IsAuthenticated())
    {
        return;  //user not logged in
    }

   //the rest of the codes
}

.. and here...

app.UseEndpoints(endpoints => 
{
    endpoints.MapControllers().RequireAuthorization();
});
like image 36
Rosdi Kasim Avatar answered Mar 05 '23 17:03

Rosdi Kasim