Search code examples
c#authenticationasp.net-corejwtasp.net-identity

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


I have added a JWT middleware to my application:

app.UseJwtBearerAuthentication(options => { options.AutomaticAuthenticate = true;} )

Ideally what I want to achieve is that all controller actions are protected by default (there were filters for that in previous ASP.NET), and I will put Anonymous on those that I want public or perhaps Authorize("SomePolicy") if I want additional policies, but I want that without a token the API cannot be accessed at all. How do I do this in the ASP.NET Core?


Solution

  • 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.