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

asp.net Core-MvcAuthorize Attributeasp.net Authorization

asp.net Core-Mvc Problem Overview


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?

asp.net Core-Mvc Solutions


Solution 1 - asp.net Core-Mvc

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

Solution 2 - asp.net Core-Mvc

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLukasz MkView Question on Stackoverflow
Solution 1 - asp.net Core-MvcblowdartView Answer on Stackoverflow
Solution 2 - asp.net Core-MvcRohan ShenoyView Answer on Stackoverflow