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

The below example worked for me when using .NET 5, the accepted answer doesn't seem to work for .NET 5

services.AddMvc(config => {
    config.Filters.Add(new AuthorizeFilter());
});

You can still use filters as in this example:

services.AddMvc(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                 .RequireAuthenticatedUser()
                 .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

The policy in this example is very simple but there a lots of ways to configure a policy for various requirements, roles etc.


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.