We have a custom AuthorizationFilterAttribute
for decorating WebApi controller actions that takes an enum parameter to define the level of access.
public enum AuthLevel
{
Any = 1,
Client = 2,
Server = 4
}
[AttributeUsage(AttributeTargets.Method)]
public class CustomAuthorizeAttribute : AuthorizationFilterAttribute
{
private readonly AuthLevel _authLevel;
public CustomAuthorizeAttribute(AuthLevel authLevel)
{
_authLevel = authLevel;
}
public override void OnAuthorization(HttpActionContext actionContext)
{
...
}
}
Usage:
public class TestController : ApiController
{
[HttpGet, Route("api/test")]
[CustomAuthorizeAttribute(AuthLevel.Client)]
public IHttpActionResult Get()
{
return Ok();
}
[HttpGet, Route("api/testasync")]
[CustomAuthorizeAttribute(AuthLevel.Server)]
public async Task<IHttpActionResult> GetAsync()
{
return Task.FromResult(Ok());
}
}
While there's no substitution for good integration tests, I'd like to be able to unit test that this attribute has been defined on the controller action with the correct enum value. It also has to work with both standard and async methods.
I created a couple of extension methods for this:
Usage: