How to add global `AuthorizeFilter` or `AuthorizeAttribute` in ASP.NET Core?

You can also use the below code. This is using a type rather than an instance.

services.AddMvc(options =>
{
    options.Filters.Add(typeof(AuthorizeFilter));
});

And using Dependency Injection you can resolve the policy Object.


From docs:

You can register a filter globally (for all controllers and actions) by adding it to the MvcOptions.Filters collection in the ConfigureServices method in the Startup class:

You can not add AuthorizeAttribute into MvcOptions.Filters . Create an AuthorizationPolicy and use AuthorizeFilter:

var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .RequireRole("Admin", "SuperUser")
        .Build();

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

In case if you are using the Razor Page flavor of the ASP.NET Core 2.0 you could add global filters as follows:

services.AddMvc()
.AddRazorPagesOptions(options =>
        {
            options.Conventions.AuthorizeFolder("/"); // Require users to be authenticated.
            options.Conventions.AuthorizeFolder("/", "YourPolicyName"); // Require a policy to be full filled globally.
        });