Is it possible to use async/await in MVC 4 AuthorizeAttribute?

The only override I see exposed on MVC’s AuthorizeAttribute is public override void OnAuthorization( AuthorizationContext filterContext ) which is not suitable for use with async/await because it doesn’t return a Task. Is there another way to create an AuthorizeAttribute in MVC that allows the use of async/await?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

ASP.NET MVC today does not support asynchronous filters. Please vote.

However, ASP.NET “vNext”, announced at TechEd this week, will support asynchronous filters for MVC.

Method 2

With asp.net core being released, Stephen Cleary’s answer is correct and the ideal way to go if you are running the latest asp.net core.

For those that haven’t updated yet, I was able to work around my issue using an async HttpModule that passes state into the AuthorizationFilter via HttpContext.Items. I added more detail about my solution here – http://evandontje.com/2017/08/15/solutions-for-async-await-in-mvc-action-filters/

Method 3

for those who do not yet have the joy of being on .net core, but you can use this method from ASP.NET Web API 2 :

OnAuthorizationAsync override :

public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellation)

for example you can call a async webapi service like this :

 public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellation)
    {
        await base.OnAuthorizationAsync(actionContext, cancellation);

        if (await IsUserAdminAsync()) /* call any async service */
            return;
        this.HandleUnauthorizedRequest(actionContext);
    }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x