How to protect all controllers by default with bearer token in ASP.NET Core?

Starting with .Net 6 we can do this (if using minimal hosting model recommended by Microsoft):

app
  .MapControllers()
  .RequireAuthorization(); // This will set a default policy that says a user has to be authenticated

Starting with .Net Core 3 we can do this:

app.UseEndpoints(endpoints =>
{
    endpoints
        .MapControllers()
        .RequireAuthorization(); // This will set a default policy that says a user has to be authenticated
});

It is possible to change default policy or add a new policy and use it as well.

P.S. Please note that even though the method name says “Authorization”, by default it will only require that the user is Authenticated. It is possible to add more policies to extend the validation though.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)