Apply Authorization with a policy to all controllers within a namespace in asp.net core

Viewed 1963

Using ASP.NET 5 I've implemented an Authorization Policy that I'd like to apply to all controllers within a namespace, but NOT to all controllers in the project. Is there a way to do this other than add the attribute [Authorize(Policy="MyPolicy")] to each controller individually? I'd like to avoid the risk that another dev adds a new controller to the namespace but forgets to apply the policy.

It looks like this when doing it manually:

[ApiController]
[Authorize(Policy="MyPolicy")]
[Route("api/DoStuff")]
public class MyController : ControllerBase
{ 

    [HttpGet("foo")]
    public GetFoo() 
    {
    }

}
3 Answers

Why not just create a controller to inherit from and then apply it to whatever controllers you want? Something like

[Authorize(Policy="MyPolicy")]
public class BaseProtectedController : ControllerBase
{

}

And then inherit from this controller whenever you need Authorize

public class SomeProtectedController : BaseProtectedController
{

}

Is there a way to do this other than add the attribute [Authorize(Policy="MyPolicy")] to each controller individually? I'd like to avoid the risk that another dev adds a new controller to the namespace but forgets to apply the policy.

You can try to add an authorization filter and specify PolicyName, like below.

services.AddControllers(config =>
{
    config.Filters.Add(new AuthorizeFilter("MyPolicy"));
});

You could implement the IControllerModelConvention and manage the policies according to the namespace of the controller from there

AddAuthorizeFiltersControllerConvention.cs

public class AddAuthorizeFiltersControllerConvention : IControllerModelConvention
{
    public void Apply(ControllerModel controller)
    {
        if (controller.ControllerType.Namespace == "My.Admin.Namespace")
        {
            controller.Filters.Add(new AuthorizeFilter("AdminPolicy"));
        }
        else 
        {
            controller.Filters.Add(new AuthorizeFilter("DefaultPolicy"));
        }
    }
}

Then you can apply this controller model convention to your controllers in the ConfigureServices

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // ... Cutting everything else in the ConfigureServices for simplicity

    services.AddControllers(options => {
        options.Conventions.Add(new AddAuthorizeFiltersControllerConvention());
    });
}

Another example of this can be found here http://hpblogs.com/blogs/add-authorize-policy-dynamically-to-all-controllers-in-asp-net-core-3-1/48

Related