Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 657
xird Avatar asked Feb 01 '17 05:02

xird


People also ask

How do I register a global filter in .NET core?

Add( new AuthorizeAttribute() { Roles = "Admin, SuperUser" }); In . Net Core, we can add the filters globally by adding it to the MvcOptions. Filters collection in the ConfigureServices method in the Startup class.

Do we have global ASAX in .NET core?

If global. asax or its parent HttpApplication was part of ASP.NET and not windows native drivers then why can't ASP.NET Core hosting module directly communicate to it without having startup.

How add Authorize attribute in core in asp net?

Authorization in ASP.NET Core is controlled with AuthorizeAttribute and its various parameters. In its most basic form, applying the [Authorize] attribute to a controller, action, or Razor Page, limits access to that component to authenticated users. Now only authenticated users can access the Logout function.

How do I use authorized filter in net core?

Filters in ASP.NET Core allow code to run before or after specific stages in the request processing pipeline. Built-in filters handle tasks such as: Authorization, preventing access to resources a user isn't authorized for. Response caching, short-circuiting the request pipeline to return a cached response.


4 Answers

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));
});
like image 52
tmg Avatar answered Oct 08 '22 09:10

tmg


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.

like image 45
maxspan Avatar answered Oct 08 '22 08:10

maxspan


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.
        });
like image 28
BuddhiP Avatar answered Oct 08 '22 09:10

BuddhiP


Adding a new answer to expand on @maxspan's answer which I found immensely helpful.

I needed to enforce the presence of bearer token in my API. Here's what I ended up doing.

  • Created an authorization policy and injected that as a dependency in Startup.cs.
AuthorizationPolicy policy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();
services.AddSingleton(policy);
  • Created a filter called BearerTokenAuthorizationFilter which extends from AuthorizeFilter and retrieved the policy dependency.
public class BearerTokenAuthorizationFilter : AuthorizeFilter
{
  private readonly AuthorizationPolicy _policy;

  public BearerTokenAuthorizationFilter(AuthorizationPolicy policy) : base(policy)
  {
      _policy = policy;
  }

  public override async Task OnAuthorizationAsync(AuthorizationFilterContext context)
  {
    //Use the policy here...
  }
}
  • Applied this filter on all controllers in my API.
services.AddControllers(options =>
{
    options.Filters.Add(typeof(BearerTokenAuthorizationFilter));
});
like image 30
Gaurav Mantri Avatar answered Oct 08 '22 08:10

Gaurav Mantri