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

后端 未结 3 1992
情歌与酒
情歌与酒 2020-12-03 07:01

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

GlobalFilters.Filters.Add(new AuthorizeAttribute() { Roles = \"Admin, S         


        
相关标签:
3条回答
  • 2020-12-03 07:08

    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));
    });
    
    0 讨论(0)
  • 2020-12-03 07:26

    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.
            });
    
    0 讨论(0)
  • 2020-12-03 07:33

    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.

    0 讨论(0)
提交回复
热议问题