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

24,581

Solution 1

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));
});

Solution 2

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.

Solution 3

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.
        });
Share:
24,581
xird
Author by

xird

Updated on July 09, 2022

Comments

  • xird
    xird almost 2 years

    In ASP.NET MVC 4 and below we just add the following in Global.asax:

    GlobalFilters.Filters.Add(new AuthorizeAttribute() { Roles = "Admin, SuperUser" });
    

    Any idea how to do this in ASP.NET Core MVC?