Add global Authorization filter in ASP.NET Core 2.0

Navin picture Navin · Nov 29, 2017 · Viewed 7.5k times · Source

in my ConfigureServices i have created a policy based authorization

 services.AddAuthorization(options =>
 {
     options.AddPolicy("test", policy => policy.Requirements.Add(new TestRequirement()));
 });

and registered the handler as below

services.AddSingleton<IAuthorizationHandler, CustomAuthorizationHandler>();

but rather than applying authorization on top of all controller like this

[Authorize(Policy = "test")]

Is there a way to apply authorize attribute globally like in MVC 5?

I tried

services.AddMvc(config=>config.Filters.Add(new AuthorizeAttribute("test")))

but I think something wrong here.

Answer

Muqeet Khan picture Muqeet Khan · Nov 29, 2017

You should first create a policy using the AuthorizationPolicyBuilder in ConfigureServices and then you can do the following:

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

Where policy is your test policy ...