How to protect all default controllers with a token carrier in ASP.NET Core (asp.net 5)?

I added the JWT middleware to my application:

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

There is nothing funny in that he throws an exception of 500 (should be changed to 401 in subsequent releases) for ALL actions, even those that are not protected at all (do not have the authorize attribute). It seems to me that this is wrong, but perhaps I myself am doing something wrong.

Ideally, I want all actions to be protected by default (there were filters in the previous ASP.NET), and I will put "Anonymous" on those whom I want to publish or, possibly, "Authorize" (SomePolicy), if I additional policies are needed, but I want the API to be unable to access at all without the token. How to do it in the new ASP.NET (I know that I can inherit from some controller with this attribute, but I hope there is a better way to do this)?

+4
source share
1 answer

You can use filters, as in this example:

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

, , ..

+17

Source: https://habr.com/ru/post/1625846/


All Articles