'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?
Solution 1:[1]
From docs:
You can register a filter globally (for all controllers and actions) by adding it to the
MvcOptions.Filterscollection in theConfigureServicesmethod in theStartupclass:
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:[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:[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.
});
Solution 4:[4]
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
BearerTokenAuthorizationFilterwhich extends fromAuthorizeFilterand 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));
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tmg |
| Solution 2 | maxspan |
| Solution 3 | BuddhiP |
| Solution 4 | Gaurav Mantri |
