Chitika

March 14, 2012

ASP.NET MVC 4 WebAPI authorization

In the examples of ASP.NET MVC 4 WebAPI you can find that authorization is really easy.
You just have to add [Authorize] attribute to your controller or for some actions which need it.

And if you do this you will expect that your WebAPI will return error code 401 (Not authorized) to your client.

But unfortunately it's not happened.
And you can ask: what will happen in the real world?
I can answer: your browser just get the 302 (Found) status code and will redirect you to the login page.

I think it's not expected behavior for you. Because you want to get just 401 status code in the client.

And I can show you how you can achieve it.

1. Please, double sure that you use AuthorizeAttribute from the System.Web.Http library instead of one from the System.Web.Mvc.

2. Add a directory and two classes to your code which should "FIX" it:

- Add App_Start directory to your solution.
       We will create two classes in this directory in a minute.

Add first class into that folder:  
       This class is a HTTP module which do all the 'magic'.
       The 'magic' is simple - just set the marker in PosrReleaseRequestState event if this is an ajax request and if our action returns status code equals to 401 (Unauthorized) or 403 (Forbidden). Then in OnEndRequest we have to check is this marker exists, and if yes, then set the returned status code from an action back.
public class AjaxFormsAuthenticationModule : IHttpModule

    {

        private const string FixupKey = "__WEBAPI:Authentication-Fixup";

        public void Dispose()

        {

        }

        public void Init(HttpApplication context)

        {

            context.PostReleaseRequestState += OnPostReleaseRequestState;

            context.EndRequest += OnEndRequest;

        }

        private void OnPostReleaseRequestState(object source, EventArgs args)

        {

            var context = (HttpApplication)source;

            var response = context.Response;

            var request = context.Request;

            bool isAjax = request.Headers["X-Requested-With"] == "XMLHttpRequest";

            if ((response.StatusCode == 401 || response.StatusCode == 403) && isAjax)

            {

                context.Context.Items[FixupKey] = response.StatusCode;

            }

        }

        private void OnEndRequest(object source, EventArgs args)

        {

            var context = (HttpApplication)source;

            var response = context.Response;

            if (context.Context.Items.Contains("__WEBAPI:Authentication-Fixup"))

            {

                response.StatusCode = (int)context.Context.Items[FixupKey];

                response.RedirectLocation = null;

            }

        }

    }

Add second class into that folder:
       This class will just register our HTTP module for our application..
using Microsoft.Web.Infrastructure.DynamicModuleHelper;

[assembly: PreApplicationStartMethod(typeof(FormsAuthenticationFixer), "Start")]

namespace LoginVS11.App_Start

{

    public static class FormsAuthenticationFixer

    {

        public static void Start()

        {

            DynamicModuleUtility.RegisterModule(typeof(AjaxFormsAuthenticationModule));

        }

    }

}

That's all.

After that all of your ajax requests will get the 401 status code if your client is not authorized yet.

71 comments:

  1. Thanks, this really helped explain it.

    How would you go about handling authentication of users in a WebAPI?

    ReplyDelete
    Replies
    1. It's not easy question, because if you would like to strict go with RESTful kind of WebAPI then you have to create some token/keys mechanism between client and server.

      But if you are ready to move a little bit from strict RESTful way then of course there are a lot of simplest ways to do authentication.

      I will describe one of them in my next topic.

      Delete
  2. Any chance you have a guide about how to autherize using restapi in mvc4? I want to login from a WP7 application without the user going to a website so I guess I have to return a AuthorizeAttribute somehow in the Header?

    ReplyDelete
  3. Couldn't you just use System.Web.Http.AuthorizeAttribute instead of System.Web.Mvc.AuthorizeAttribute? If I'm not mistaken, it returns an error response with a 401 status code.

    Sam

    ReplyDelete
  4. I can think of many scenarios when building device agnostic mobile applications that need to communicate with a service where a token based or ApplicationID / secret key type of solution would be useful. Any thoughts on best practices would be really helpful.

    ReplyDelete
  5. Dude, this looked pretty interesting until I saw that you defined a constant and then didn't bother to use it on line 53.

    ReplyDelete
  6. Good to become visiting your weblog again, it has been months for me. Nicely this article that i've been waited for so long. I will need this post to total my assignment in the college, and it has exact same topic together with your write-up. Thanks, good share. 먹튀검증

    ReplyDelete
  7. This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea. 먹튀검증

    ReplyDelete
  8. I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me. I am appreciating it 강남출장안마

    very much! Looking forward to another great article. Good luck to the author! All the best!

    ReplyDelete
  9. the internet for information and found your blog. I am impressed with the information you have on this blog. 토토검증커뮤니티

    ReplyDelete
  10. I was searching for this sort of data and delighted in perusing this one. Continue posting. Much obliged for sharing. 먹튀검증커뮤니티

    ReplyDelete
  11. Sweet blog! I found it while browsing on Yahoo News.
    Do you have any tips on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get
    there! Thank you
    Also visit my site:강남오피

    ReplyDelete
  12. 이 웹사이트를 방문해서 이 단락에 대한 모든 친구들의 견해를 읽는 것은 매우 주목할만하다.우리카지노

    ReplyDelete
  13. you have got a excellent weblog here! do you need to develop invite posts on my own weblog?
    먹튀검증

    ReplyDelete
  14. 있습니다.대략적으로 알려진 업체 수만 하더라도 5,000개가 넘는다고 말합니다. 한 달도 버티지 못 하고 문을 닫는 곳이 아주 많습니다. 저희 역시스포츠배팅을 즐기는 사람들입니다. 다양한 곳에서 게임을 해 왔으며 먹튀 또한 여러 번 당하였습니다. 심지어 검증업체에서 커미션도 지급받지못 한 경우가 있습니다. 산전수전 다 겪으면서 여러 업체들을 컨택하여 왔으며 현재 검증 된 업체들은 지난 2년 동안 저와 가족방 식구들이 이용하면서 단 한 번의 사고도 없는 가장 안전한 메이저업체라고 자신있게 말 할 수 있습니다. 먹튀 때문에 쉽게 이용하지 못 하시겠다구요? 그렇다면 안심하세요. 저희 가족방은 24시간 수 천명의 인원들이 지켜보는 대한민국 최대 규모의 단체방입니다. 안심하고 검증업체를 이용하셔도 됩니다
    토토사이트.

    ReplyDelete
  15. What a perfect place to be.토토사이트 I'm glad I got a lot of information.

    ReplyDelete
  16. I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much 먹튀검증업체

    ReplyDelete
  17. Actually when someone doesn't understand then its up to other viewers that they will assist, so here it takes place.

    Here is my web site - 오피사이트


    ReplyDelete
  18. I got a web site from where I be capable of really obtain valuable information regarding my study and knowledge.
    Great Article… Good Job… Thanks For Sharing…

    Website:ライブカジノの

    ReplyDelete
  19. I’m gone to inform my little brother, that he should also pay a quick visit this blog on regular basis to obtain updated from most recent
    news.
    바카라

    ReplyDelete
  20. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up. Great work.
    카지노사이트

    ReplyDelete
  21. the following time i read a blog, hopefully it does no longer fail me simply as a great deal as this particular one. I imply, i know it become my preference to examine, however i without a doubt believed you'll have something beneficial to mention. All i listen is a group of crying approximately something that you can fix in case you weren’t too busy looking for interest. When i to start with commented i seem to have clicked on the -notify me while new comments are added- checkbox and any further every time a comment is delivered i recieve four emails with the precise equal remark. Is there a way you're able to get rid of me from that service? An impressive proportion! I’ve just forwarded this onto a colleague who has been undertaking a bit homework on this. And he truely ordered me dinner without a doubt due to the fact i discovered it for him… lol. So allow me to reword this…. Thanks for the meal!! However yeah, thanx for spending time to talk about this subject matter here to your site. 모두의토토

    ReplyDelete
  22. i am so pleased i located your blog website, i honestly situated you by mistake, even as i used to be taking a examine on google for any other factor, in any case i am below now similarly to additionally would in reality similar to to insist supply way to for an outstanding blog submit together with an all-around unique net site. I'm honestly taking part in reading your properly written articles. It looks as if you spend plenty of effort and time for your blog. I have bookmarked it and i'm searching ahead to reading new articles. Hold up the good paintings. That is my first time go to in your weblog and i'm very interested in the articles which you serve. Offer sufficient expertise for me. Thank you for sharing beneficial and don’t forget about, maintain sharing beneficial data: 토토서치

    ReplyDelete
  23. Incredible! This blog lo?ks exactly ?ike my o?d one!
    It’s on a totally d?fferent subject b?t it ?as pretty muc?
    t?e ?ame layout ?nd design. Outstanding choice ?f colors!
    송송넷

    ReplyDelete
  24. Around the world, ports are congested as a result of the rapid rebound in demand for commodities and goods as much of the global economy has recovered from the pandemic. In turn, shipping costs have soared, and companies wanting to move goods around are struggling because there just aren't enough ships or containers available.
    https://www.yert200.com

    ReplyDelete
  25. "This experience today of the rising energy prices is a clear wake up call... that we should accelerate the transition to clean energy, wean ourselves off the fossil fuel dependency," a senior EU official told reporters as the European Commission unveiled a series of measures aimed at tackling the crisis.
    https://www.shine900.com

    ReplyDelete
  26. driven by increased global demand as the world recovers from the pandemic and lower-than-expected natural gas deliveries from
    https://www.gain777.com

    ReplyDelete
  27. "Winter is coming and for many electricity costs are larger than they have been for a decade," Energy Commissioner Kadri Simson told reporters
    https://www.kkr789.com

    ReplyDelete
  28. Wholesale gas prices — which have surged to record highs in France, Spain, Germany and Italy — are expected to remain high through the winter. Prices are expected to fall in the spring, but remain higher than the average of past years, according to the Commission. Most EU countries rely on gas-fired power stations to meet electricity demand, and about 40% of that gas comes from Russia, according to Eurostat.
    https://www.aace777.com

    ReplyDelete
  29. Simson said that the Commission's initial assessment indicates that Russia's Gazprom has been fulfilling its long-term contracts "while providing little or no additional supply."
    https://www.qqueen700.com

    ReplyDelete
  30. Kremlin spokesman Dmitry Peskov told journalists on Wednesday that Russia has increased gas supplies to Europe to the maximum possible level under existing contracts, but could not exceed those thresholds. "We can say that Russia is flawlessly fulfilling all contractual obligations," he said.
    https://www.rcasinosite.com

    ReplyDelete
  31. Measures EU states can take to help consumers and businesses cope with soaring electricity costs include emergency income support to households to help them pay their energy bills, state aid for companies, and targeted tax reductions. Member states can also temporarily delay bill payments and put in place processes to ensure that no one is disconnected from the grid.
    https://www.hgame789.com

    ReplyDelete
  32. Hi, I do believe this is a great web site. I stumbledupon it ;) I will come back yet again since I saved as a favorite it.
    Money and freedom is the greatest way to change, may you be rich and continue to help other people.
    카지노

    ReplyDelete
  33. That's a really impressive new idea! casino api It touched me a lot. I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.


    ReplyDelete
  34. Thanks , I’ve recently been searching for information about this subject for ages and yours is the greatest I’ve came upon so far. That's a good post. 카지노사이트
    It was a really good article. Good read. You will be visiting this blog more often. Here is my website. Please also visit my site and leave your comments.

    ReplyDelete
  35. I accidentally searched and visited your site. I still saw several posts during my visit, but the text was neat and readable. I will quote this post and post it on my blog. Would you like to visit my blog later? 메가슬롯


    ReplyDelete
  36. Your explanation is organized very easy to understand!!! I understood at once. Could you please post about 먹튀검증업체?? Please!!


    ReplyDelete
  37. I think your writing will help me, can you come to me once and help? My site is "메가슬롯


    ReplyDelete
  38. Your post has really helped me a lot. I live in a different country than you, but I believe it will help a lot in my country. 샌즈카지노 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.


    ReplyDelete
  39. I definitely enjoying every little bit of it. It is a great website and nice share. I want to thank you. Good job! You guys do a great blog, and have some great contents. Keep up the good work. s19xp

    ReplyDelete
  40. wow... what a great blog, this writter who wrote this article it's realy a great blogger, this article so inspiring me to be a better person 온라인카지노

    ReplyDelete
  41. Very good points you wrote here..Great stuff...I think you've made some truly interesting points.Keep up the good work 안전놀이터

    ReplyDelete
  42. Hello, I read the post well. casino online It's a really interesting topic and it has helped me a lot. In fact, I also run a website with similar content to your posting. Please visit once


    ReplyDelete
  43. I've been troubled for several days with this topic. 슬롯사이트, But by chance looking at your post solved my problem! I will leave my blog, so when would you like to visit it?


    ReplyDelete
  44. From some point on, I am preparing to build my site while browsing various sites. It is now somewhat completed. If you are interested, please come to play with 바카라사이트!!


    ReplyDelete
  45. webgirls When it comes to preventing candidiasis, victims frequently have their operate eliminate for them. This is because candidiasis can readily grow to be chronic and on-going. Knowing that, in the following paragraphs, we will present a wide range of some of the best verified candidiasis remedy and prevention ideas about.

    ReplyDelete
  46. https://gameeffect.xyz Many people have cherished the game of baseball for many years. There are actually fans around the world, from devoted tiny-leaguers to perish-hard spectators. This article has tips to prove how enjoyable baseball is really.

    ReplyDelete
  47. https://gameboot.xyz The truth is them on publications and on Television set, men and women who appear to be their biceps and triceps and thighs will explode his or her muscle tissue are extremely large! There is absolutely no require for you to take your body to this degree when you don't desire to, because the straightforward techniques on this page will enable you to develop muscle tissue within a healthy approach.

    ReplyDelete
  48. I read your Article very carefully it is really very good bitmain antminer s19j pro

    ReplyDelete
  49. When I initially commented I appear to have clicked on the -Notify me when new comments are added- checkbox and now every time a comment is added I receive four emails with the same comment. There has to be an easy method you can remove me from that service? Thanks! What i don’t understood is actually how you’re now not really much more well-favored than you may be now. You’re very intelligent. You realize therefore considerably when it comes to this subject, produced me for my part imagine it from so many various angles. Its like men and women are not involved unless it is one thing to do with Girl gaga! Your individual stuffs great. Always handle it up! 먹튀검증사이트

    ReplyDelete
  50. What i do not realize is if truth be told how you’re no longer actually a lot more smartly-liked than you may be right now. You are very intelligent. You realize therefore considerably relating to this matter, made me for my part believe it from so many various angles. Its like men and women aren’t fascinated until it is something to do with Girl gaga! Your personal stuffs outstanding. Always maintain it up! Well I truly liked studying it. This subject provided by you is very practical for correct planning. What’s up, I read your blog daily. Your writing style is 메이저사이트

    ReplyDelete
  51. An outstanding share! I’ve just forwarded this onto a co-worker who had been doing a little homework on this. And he actually ordered me dinner due to the fact that I discovered it for him… lol. So allow me to reword this…. Thanks for the meal!! But yeah, thanx for spending the time to talk about this issue here on your web site. It feels good to hear the fulfilling thud of a poker chip after you toss it down the desk. Now there is 1 other tip you should utilize if you want to learn how to perform. He started taking part in the sport fairly often on almost every weekend. What does matter is that you handle that money so that your bankroll increases over time. So, the more you Rake the more you get back again! Having a buddy or two to assist adds enjoyable and satisfaction. 먹튀검증

    ReplyDelete
  52. After I originally left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on every time a comment is added I receive four emails with the same comment. Perhaps there is an easy method you are able to remove me from that service? Many thanks! Greetings! Very helpful advice in this particular article! It's the little changes which will make the most important changes. Many thanks for sharing!| You are so interesting! I do not think I've read a single thing like this before. So wonderful to find someone with a few original thoughts on this subject. Really.. thank you for starting this up. This site is something that's needed on the internet, someone with a bit of originality! It­s hard to come by educated people about this subject, however, you seem like you know what youíre talking about! Thanks 승인전화없는토토사이트

    ReplyDelete
  53. An impressive share! I’ve just forwarded this onto a co-worker who had been doing a little research on this. And he in fact ordered me dinner because I discovered it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanx for spending the time to discuss this subject here on your blog. Your style is very unique in comparison to other people I have read stuff from. Thanks for posting when you have the opportunity, Guess I will just book mark this site. Good post. I learn something new and challenging on websites I stumbleupon everyday. It’s always interesting to read content from other writers and use something from other websites. 안전놀이터순위

    ReplyDelete
  54. The next time I read a blog, Hopefully it does not fail me just as much as this particular one. I mean, I know it was my choice to read, but I truly believed you would have something helpful to say. All I hear is a bunch of crying about something that you could fix if you weren’t too busy searching for attention. After I initially commented I seem to have clicked on the -Notify me when new comments are added- checkbox and from now on every time a comment is added I recieve 4 emails with the exact same comment. Is there a way you are able to remove me from that service? An impressive share! I’ve just forwarded this onto a colleague who has been conducting a little homework on this. And he actually ordered me dinner simply because I discovered it for him… lol. So allow me to reword this…. Thanks for the meal!! But yeah, thanx for spending time to talk about this topic here on your site. 토토지식백과

    ReplyDelete
  55. Impressive web site, Distinguished feedback that I can tackle. Im moving forward and may apply to my current job as a pet sitter, which is very enjoyable, but I need to additional expand. Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. Thanks for picking out the time to discuss this, I feel great about it and love studying more on this topic. It is extremely helpful for me. Thanks for such a valuable help again. 먹튀검증백과

    ReplyDelete
  56. Good post. I learn something new and challenging on blogs I stumbleupon everyday. It’s always exciting to read through articles from other writers and practice a little something from other websites. Howdy! This blog post could not be written much better! Reading through this post reminds me of my previous roommate! He constantly kept talking about this. I will send this post to him. Pretty sure he’ll have a great read. I appreciate you for sharing! Greetings! Very helpful advice in this particular article! It’s the little changes that produce the largest changes. Thanks a lot for sharing! 먹튀패스

    ReplyDelete
  57. I wish to point out my appreciation for your kind-heartedness giving support to people who really want help with the field. Your real commitment to getting the solution along appeared to be quite functional and have specifically permitted some individuals like me to arrive at their desired goals. Your personal invaluable guidelines entails this much to me and far more to my colleagues. Many thanks; from each one of us. My husband and i have been very delighted that Peter could round up his basic research from your ideas he acquired while using the web pages. It is now and again perplexing to just possibly be making a gift of guides which the others have been trying to sell. And now we do understand we’ve got the writer to give thanks to because of that. All of the illustrations you made, the easy web site navigation, the friendships you will help to engender – it’s got most overwhelming, and it’s really making our son in addition to us reason why the issue is brilliant, which is rather pressing. Thanks for the whole thing! 헤이먹튀

    ReplyDelete
  58. An impressive share, I simply offered this onto a colleague that was doing a little evaluation on this. As well as he in fact bought me breakfast due to the fact that I discovered it for him. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the moment to review this, I really feel strongly concerning it and like reading more on this subject. Ideally, as you end up being experience, would certainly you mind upgrading your blog site with more information? It is very helpful for me. Big thumb up for this post! Quality posts is the secret to interest the people to visit the site, that’s what this web page is providing.| Nice post. I learn something totally new and challenging on websites I stumbleupon every day. It’s always interesting to read through articles from other authors and practice a little something from other websites. 먹튀대피소

    ReplyDelete
  59. This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post . Of course, your article is good enough, but I thought it would be much better to see professional photos and videos together. There are articles and photos on these topics on my homepage, so please visit and share your opinions. Your style is really unique in comparison to other people I have read stuff from. Many thanks for posting when you have the opportunity, Guess I’ll just bookmark this web site. 토토검증

    ReplyDelete
  60. Pretty element of content. I simply stumbled upon your website and in accession capital to claim that I get in fact enjoyed account your blog posts. Any way I will be subscribing to your augment or even I fulfillment you get entry to constantly rapidly. It’s best to take part in a contest for among the finest blogs on the web. I will suggest this website! This site is mostly a stroll-via for all of the info you wished about this and didn’t know who to ask. Glimpse right here, and also you’ll positively uncover it. Wow, amazing weblog structure! How lengthy have you been running a blog for? you make blogging glance easy. The entire glance of your site is fantastic, as smartly as the content! This is a great blog. I’m really glad I have found this info. 안전토토사이트

    ReplyDelete
  61. I am so pleased I situated your blog site, I actually situated you by mistake, while I was taking a look at on google for another point, Anyways I am below now in addition to additionally would certainly just like to insist give thanks to for an outstanding blog post along with an all-around entertaining internet site. Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has the same topic with your article. Thanks, great share 먹튀마루

    ReplyDelete
  62. Interesting. I will do some more research and thanks! 검증카지노

    ReplyDelete
  63. I've never seen such a place full of useful writings in the world. I have a lot of very helpful articles. I will visit often and read it.

    ReplyDelete