We've recently implemented API authentication by implementing a custom AuthorizationFilterAttribute, using credentials stored in Azure Document DB. DocDB mandates everything use Async.
Through experimenting we found that WebApi2 synchronous controllers will use the OnAuthorizationAsync if present, and OnAuthorization if no async method. We also found that asyc controller methods can use either auth method. But I'm not 100% sure it is working correctly. We only saw that code did hit breakpoints.
Oddly, you can also override OnAuthorization mark it as async
public async override Task OnAuthorization(....)
This last method compiles and executes fine, but the controller will not wait for the auth filter to finish executing before the action method begins. Usually the result is an ASP error:
An asynchronous module or handler completed while an asynchronous operation was still pending
Seems like this manipulation of the override should have been a compile error and not allowed.
Regardless.... There are many mysteries about AuthorizationFilterAttribute and a few other posts exist about the confusion. Custom Authorization in Asp.net WebApi - what a mess?
My question is how do you know which will execute and in which order of precedence? It does appear if both exist in the filter, only one method is executed.
If your controller action is async, must you override the OnAuthorizationAsync method?
If you have async await in your auth logic, and are forced to use OnAuthorizationAsync (like I am), does this then mean I have to change all my controller actions to now all be async controller actions?
I can't find any documentation that lays out scenarios for async action filters.