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

15,867

Solution 1

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

app.MapControllers().RequireAuthorization();

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.

Solution 2

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.

Share:
15,867

Related videos on Youtube

Ilya Chernomordik
Author by

Ilya Chernomordik

You know, everyone wants a badge, so I have to write something in here :)

Updated on June 07, 2022

Comments

  • Ilya Chernomordik
    Ilya Chernomordik almost 2 years

    I have added a JWT middleware to my application:

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

    No the funny thing is that it throws 500 exception (should be changed to 401 in later releases) for ALL actions, even those that are not protected at all (don't have authorize attribute). It seems to me that this is wrong but maybe I am doing something wrong myself.

    Ideally what I want to achieve is that all 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 new ASP.NET (I know I can inherit from some controller with this attribute, but I hope there is a better way of doing it)?

  • Joe Audette
    Joe Audette over 8 years
    you can find additional authorization examples here: github.com/blowdart/AspNetAuthorizationWorkshop
  • Ilya Chernomordik
    Ilya Chernomordik over 8 years
    Thanks, I will try, but do you know what to do with the problem of jwt middleware throwing exceptions for public API?
  • Ilya Chernomordik
    Ilya Chernomordik over 8 years
    I have made a separate question for that: stackoverflow.com/questions/34995518/…. You answer fixed the original problem though, thanks :)
  • bvj
    bvj over 3 years
    I guess RequireAuthorization implies Authentication.
  • Ilya Chernomordik
    Ilya Chernomordik over 3 years
    You can check the comment in the code that explains exactly this: it adds the default policy for all controllers where authorization means authentication only (default policy). This can be further configured or changed by using policies. But the naming is not perfect and quite confusing, I agree
  • Bernoulli IT
    Bernoulli IT over 2 years
    Same as the always confusing 401 Unauthorized which should have been named Unauthenticated. MDN: "Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response."
  • Juan Stoppa
    Juan Stoppa over 2 years
    this doesn't seem to work for .NET 5, you need to add a policy in AuthorizationPolicyBuilder (e.g. AuthorizationPolicyBuilder(new string [] { "defaultPolicy" })