Vaughan Reid's blog

Using a custom authorization filter in ASP.NET Core

In a previous post I showed how you can use custom middleware to disable endpoints based on configuration and attributes. It is a good way to show how middleware works but there is an easier way. You can achieve the same result by creating a custom authorization filter.

To show how, I will first add configuration in the appsetting.json file.


"DebugOptions": {
	"EnableDebugEndpoints": true
}

I will then add the corresponding POCO class and bind it in the ConfigureServices method.


public class DebugOptions
{
	public bool EnableDebugEndpoints { get; set; }
}

public void ConfigureServices(IServiceCollection services)
{
	services.Configure<DebugOptions>(options => Configuration.GetSection(nameof(DebugOptions)).Bind(options));
	//omitted the rest
}

I will then create a class that inherits from IAuthorizationFilter and add it to the relevant Controller that will use it.


public class DebugOnlyAuthorization : IAuthorizationFilter
{
	DebugOptions debugOptions;
	
	public DebugOnlyAuthorization(IOptions<DebugOptions> option)
	{
		this.debugOptions = option.Value;
	}

	public void OnAuthorization(AuthorizationFilterContext context)
	{
		if (!this.debugOptions.EnableDebugEndpoints)
		{
			context.Result = new ForbidResult();
		}
	}
}

[ApiController]
[TypeFilter(typeof(DebugOnlyAuthorization))]
public class DebugController : ControllerBase
{
    public ActionResult Get()
    {
        Return Ok();
    }


Thats it. If you try access the endpoint when the configuration is missing or disabled then you will get a 403 result.