34

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?

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207

4 Answers4

77

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.

Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • I guess RequireAuthorization implies Authentication. – bvj Jan 16 '21 at 20:43
  • 1
    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 – Ilya Chernomordik Jan 18 '21 at 08:47
  • 1
    Same as the always confusing 401 `Unauthorized` which should have been named `Unauthenticated`. [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status): "Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response." – Youp Bernoulli Nov 05 '21 at 13:31
40

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.

Joe Audette
  • 35,330
  • 11
  • 106
  • 99
  • 2
    you can find additional authorization examples here: https://github.com/blowdart/AspNetAuthorizationWorkshop – Joe Audette Jan 25 '16 at 14:27
  • Thanks, I will try, but do you know what to do with the problem of jwt middleware throwing exceptions for public API? – Ilya Chernomordik Jan 25 '16 at 14:32
  • I have made a separate question for that: http://stackoverflow.com/questions/34995518/how-to-add-token-validation-only-for-protected-actions-in-asp-net-5-asp-net-cor. You answer fixed the original problem though, thanks :) – Ilya Chernomordik Jan 25 '16 at 14:56
  • this doesn't seem to work for .NET 5, you need to add a policy in AuthorizationPolicyBuilder (e.g. AuthorizationPolicyBuilder(new string [] { "defaultPolicy" }) – Juan Stoppa Jan 27 '22 at 23:13
2

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());
});
Juan Stoppa
  • 460
  • 1
  • 4
  • 15
0

There exist a lot of solutions will tell you two of them:-

//First one
builder.Services.AddControllers(opts =>
{
    opts.Filters.Add(new AuthorizeFilter());
});

//Second one
builder.Services.AddAuthorization(opts =>
{
    opts.FallbackPolicy = new AuthorizationPolicyBuilder()
       .RequireAuthenticatedUser() 
       .Build();
});
Mahmmoud Kinawy
  • 551
  • 4
  • 11