MVC Core How to force / set global authorization for all actions?

How to force / set global authorization for all actions in MVC Core ?

I know how to register global filters - for example I have:

Setup.cs

services.AddMvc(options =>
{
    options.Filters.Add(new RequireHttpsAttribute());
});

and this works fine, but I can't add the same for Authorize:

options.Filters.Add(new AuthorizeAttribute());

I have error:

Cannot convert from 'Microsoft.AspNet.Authorization.AuthorizeAttribute()' to 'System.Type'

(Method .Add() needs IFilterMetadata type)


I know - from similar questions - that this works on MVC4-5... So something must changed on MVC Core...

Someone have any idea?


Solution 1:

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

Solution 2:

Add the following to your ConfigureServices in StartUp.cs. This is for token validation and force all calls to verify with token.

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

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

Add this to Configure method in StartUp.cs.

app.UseAuthentication();

Note: Use [AllowAnonymous] for those where you don't need it