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?
Add endpoints.MapControllers().RequireAuthorization(...);
into your endpoint configuration.
Your controller have own/explicit Route
attribute and is not covered by MapControllerRoute
call.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With