Header Ads

ASP.NET MVC5: REST Web API Authorization

When a REST Web API is created to share data across multiple devices e.g. mobile devices, desktop applications or any website, then the authorization of REST Web API becomes a vital aspect in order to protect data sensitivity from any outside breaches.

Today, I shall demonstrate a simple mechanism to authorize a REST Web API without the complex authorization process of OWIN security layer but at the same time benefiting from [Authorize] attribute.


Following are few prerequisites before you proceed any further:  

1) Knowledge of ASP.NET MVC5.  
2) Knowledge of C# programming.  
3) Knowledge of REST Web API.

You can download complete source code or you can follow step by step discussion below. The sample code is developed in Microsoft Visual Studio 2013 Ultimate.

Download Now!

Let's begin now:  

1) Create new Web API project and name it "WebApiAuthorization".  
2) Rename "ValueController.cs" file to "WebApiController.cs".
3) Now, in "WebApiController.cs" file replace following code:

using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Net;  
 using System.Net.Http;  
 using System.Web.Http;  
 namespace WebApiAuthorization.Controllers  
 {  
   [Authorize]  
   public class WebApiController : ApiController  
   {  
     // GET api/values  
     public IEnumerable<string> Get()  
     {  
       return new string[] { "Hello REST API", "I am Authorized" };  
     }  
     // GET api/values/5  
     public string Get(int id)  
     {  
       return "Hello Authorized API with ID = " + id;  
     }  
     // POST api/values  
     public void Post([FromBody]string value)  
     {  
     }  
     // PUT api/values/5  
     public void Put(int id, [FromBody]string value)  
     {  
     }  
     // DELETE api/values/5  
     public void Delete(int id)  
     {  
     }  
   }  
 }  

In above code, I simply replace some of existing string values, nothing special is done here.  

4) Now, for the authorization part, I am using HTTP Message Handlers technique. In simple essence, this technique capture HTTP request and respond accordingly. In order to use this technique, we need to inherit "DelegatingHandler" class and then hook its method SendAsync(...) that will process every hit to our REST Web API and verify our allocated authorization or API header key accordingly and then finally set our Principal after successful authorization. Principal will simply set our security context by containing information about the user whom we have claim as authorize user by using Identity Based Authorization, this will allow us to utilize [Authorize] attribute for our web api controller. So, create new folder under project root and name it "Resources->Constants". I like my code architecture clean, so, I am using constants in a resource file.  

5) Now, create a file "Resource->Constants-> ApiInfo.resx" open the file and place following constants in it i.e.


Make sure that Access Modifier is set to Public. This file will contain authorization constants that I will be using to authenticate my REST Web API.

6) Now, create new folder hierarchy under project root i.e. "Helper_Code->Common".
7) Create our authorization file and name it "Helper_Code->Common->AuthorizationHeaderHandler.cs".  
8) Open the file "Helper_Code->Common->AuthorizationHeaderHandler.cs" and replace it with the following piece of code i.e.

//-----------------------------------------------------------------------  
 // <copyright file="AuthorizationHeaderHandler.cs" company="None">  
 //   Copyright (c) Allow to distribute this code.  
 // </copyright>  
 // <author>Asma Khalid</author>  
 //-----------------------------------------------------------------------  
 namespace WebApiAuthorization.Helper_Code.Common  
 {  
   using System;  
   using System.Collections.Generic;  
   using System.Linq;  
   using System.Net.Http;  
   using System.Net.Http.Headers;  
   using System.Security.Claims;  
   using System.Security.Principal;  
   using System.Text;  
   using System.Threading;  
   using System.Threading.Tasks;  
   using System.Web;  
   using WebApiAuthorization.Resources.Constants;  
   /// <summary>  
   /// Authorization for web API class.  
   /// </summary>  
   public class AuthorizationHeaderHandler : DelegatingHandler  
   {  
     #region Send method.  
     /// <summary>  
     /// Send method.  
     /// </summary>  
     /// <param name="request">Request parameter</param>  
     /// <param name="cancellationToken">Cancellation token parameter</param>  
     /// <returns>Return HTTP response.</returns>  
     protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
     {  
       // Initialization.  
       IEnumerable<string> apiKeyHeaderValues = null;  
       AuthenticationHeaderValue authorization = request.Headers.Authorization;  
       string userName = null;  
       string password = null;  
       // Verification.  
       if (request.Headers.TryGetValues(ApiInfo.API_KEY_HEADER, out apiKeyHeaderValues) &&  
         !string.IsNullOrEmpty(authorization.Parameter))  
       {  
         var apiKeyHeaderValue = apiKeyHeaderValues.First();  
         // Get the auth token  
         string authToken = authorization.Parameter;  
         // Decode the token from BASE64  
         string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));  
         // Extract username and password from decoded token  
         userName = decodedToken.Substring(0, decodedToken.IndexOf(":"));  
         password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);  
         // Verification.  
         if (apiKeyHeaderValue.Equals(ApiInfo.API_KEY_VALUE) &&  
           userName.Equals(ApiInfo.USERNAME_VALUE) &&  
           password.Equals(ApiInfo.PASSWORD_VALUE))  
         {  
           // Setting  
           var identity = new GenericIdentity(userName);  
           SetPrincipal(new GenericPrincipal(identity, null));  
         }  
       }  
       // Info.  
       return base.SendAsync(request, cancellationToken);  
     }  
     #endregion  
     #region Set principal method.  
     /// <summary>  
     /// Set principal method.  
     /// </summary>  
     /// <param name="principal">Principal parameter</param>  
     private static void SetPrincipal(IPrincipal principal)  
     {  
       // setting.  
       Thread.CurrentPrincipal = principal;  
       // Verification.  
       if (HttpContext.Current != null)  
       {  
         // Setting.  
         HttpContext.Current.User = principal;  
       }  
     }  
     #endregion  
   }  
 } 

In above code, "Helper_Code->Common->AuthorizationHeaderHandler.cs" class inherits "DelegatingHandler" class. We have hooked the "SendAsync(...)" method and created a new method "SetPrincipal(...)" to set our authorization principal. Now, let's discuss above code chunk by chunk .i.e. In Method "SetPrincipal(...)" the following code i.e.

     // setting.  
       Thread.CurrentPrincipal = principal;  
       // Verification.  
       if (HttpContext.Current != null)  
       {  
         // Setting.  
         HttpContext.Current.User = principal;  
       }  

The above code will set our authorization principal with Identity Based Authorization model. Let's, dissect "SendAsync(...)" method step by step i.e.

      // Verification.  
       if (request.Headers.TryGetValues(ApiInfo.API_KEY_HEADER, out apiKeyHeaderValues) &&  
         !string.IsNullOrEmpty(authorization.Parameter))  
       {  
 ...  
 }  

The above line of code will verify that whether our authorize header key and credentials are empty or not. I have used combination of both header key and credentials to authorize my REST Web API. If the authorization is successful then following code will extract our authorization information form the HTTP request and store them into local variables i.e.

       var apiKeyHeaderValue = apiKeyHeaderValues.First();  
         // Get the auth token  
         string authToken = authorization.Parameter;  
         // Decode the token from BASE64  
         string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));  
         // Extract username and password from decoded token  
         userName = decodedToken.Substring(0, decodedToken.IndexOf(":"));  
         password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);  

After above code we will verify that whether the provided authorization for REST Web API hit is valid or not with the following code i.e.

       // Verification.  
         if (apiKeyHeaderValue.Equals(ApiInfo.API_KEY_VALUE) &&  
           userName.Equals(ApiInfo.USERNAME_VALUE) &&  
           password.Equals(ApiInfo.PASSWORD_VALUE))  
         {  
             ...  
         }  

If the hit to our REST Web API contains valid authorization credentials and header key then we register our principal with Identity Based Authorization model i.e.

          // Setting  
           var identity = new GenericIdentity(userName);  
           SetPrincipal(new GenericPrincipal(identity, null));  
   
9) Now, Open "Global.asax.cs" file and replace following code in it i.e.

using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Http;  
 using System.Web.Mvc;  
 using System.Web.Optimization;  
 using System.Web.Routing;  
 using WebApiAuthorization.Helper_Code.Common;  
 namespace WebApiAuthorization  
 {  
   public class WebApiApplication : System.Web.HttpApplication  
   {  
     protected void Application_Start()  
     {  
       AreaRegistration.RegisterAllAreas();  
       GlobalConfiguration.Configure(WebApiConfig.Register);  
       FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
       RouteConfig.RegisterRoutes(RouteTable.Routes);  
       BundleConfig.RegisterBundles(BundleTable.Bundles);  
       // API authorization registration.  
       GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthorizationHeaderHandler());  
     }  
   }  
 }  

In above code we have registered our authorization class within global configuration.  

10) Now, execute the project and use following link in the browser to see your newly created REST Web API method in action as follow:

 yourlink:port/api/WebApi 


In the above snippet, you will notice that since, now our REST Web API has been authorized, therefore, we cannot directly execute the REST Web API URL in the browser.  

11) Lets, test out REST Web API in REST Web API client. I am using fire fox plugin i.e. "RESTED". At, first, I simply try to hit the REST Web API without any authorization details and I will get following response i.e.


 

12) Now, I will provide the authorization and hit the REST Web API and will get following response i.e.


 

 

That's about it.

Enjoy!! coding.

113 comments:

  1. i find more new information,i like that kind of information,not only i like that post all peoples like that post,because of all given information was very excellent.

    Digital Marketing Company in Chennai

    ReplyDelete
  2. Thank you for the appreciation.

    ReplyDelete
  3. keep sharing your information regularly for my future reference. This content creates a new hope and inspiration with in me.

    Digital Marketing Company in Chennai

    ReplyDelete
  4. I will surely. Thank you once again.

    ReplyDelete
  5. I get requested to do site appraises a considerable measure and once in a while it's out and out shocking to catch wind of the battles and difficulties business visionaries and entrepreneurs confront when attempting to locate the correct web engineer. Edknt Media

    ReplyDelete
  6. I am using VS2015 and I am unable to create ApiInfo.resx, can you plz help me.

    ReplyDelete
    Replies
    1. Right click target project in solution explorer -> click add new item -> type .resx in search box and select resource file name it then click -> resource file will be created.

      Delete
  7. Our credit repair services work to fix past credit mistakes and verify credit report accuracy. Talk to a credit repair expert today!  visit website

    ReplyDelete
  8. Your post is very helpful to get some effective tips to reduce weight properly. You have shared various nice photos of the same. I would like to thank you for sharing these tips. Surely I will try this at home. Keep updating more simple tips like this. privacidadenlared.es

    ReplyDelete
  9. Good post but I was wondering if you could write a litte more on this subject? I’d be very thankful if you could elaborate a little bit further. Appreciate it..! vpn for expats

    ReplyDelete
    Replies
    1. Thank you for reaching out. Do let me know which part need more elaboration. So, I can update accordingly.

      Delete
  10. Regular visits listed here are the easiest method to appreciate your energy, which is why why I am going to the website everyday, searching for new, interesting info. Many, thank you https://www.lemigliorivpn.com

    ReplyDelete
  11. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. vpnveteran

    ReplyDelete
  12. Hello Asma,
    Nice work on the article. Really concise and highly informative.
    I would like to ask on how to go about this in a .Net Core 2.1 Project. I'll appreciate if you can direct me to another post, resources or an explanation.

    Thanks a lot

    ReplyDelete
    Replies
    1. You need to use core NBC for above tutorial to work

      Delete
  13. Regular visits listed here are the easiest method to appreciate your energy, which is why why I am going to the website everyday, searching for new, interesting info. Many, thank you get moreprivacy

    ReplyDelete
  14. Great post full of useful tips! My site is fairly new and I am also having a hard time getting my readers to leave comments. Analytics shows they are coming to the site but I have a feeling “nobody wants to be first”. https://allertaprivacy.it

    ReplyDelete
  15. Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. Webdesign bureau

    ReplyDelete
  16. One of the most neglected things when searching for a website creator is whether any web crawler optomisation (SEO) is incorporated, web developer nuneaton

    ReplyDelete
  17. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. freelance web designer peter

    ReplyDelete
  18. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. freelance web designer

    ReplyDelete
  19. There are an enormous number of organizations that embrace a quick and dishonest way to deal with SEO known as Dark Cap SEO. Webdesign

    ReplyDelete
  20. Then again, you can make due with the following best thing - Premium WordPress themes.premium wordpress blog themes

    ReplyDelete
  21. Great post about the ASP.NET MVC5. I am also a ASP.NET developer and develop .net application for my client.

    ReplyDelete
  22. hi was just seeing if you minded a comment. i like your website and the thme you picked is super. I will be back. brand identity design

    ReplyDelete
  23. This comment has been removed by a blog administrator.

    ReplyDelete
  24. Well managed article for .net and about wen API authorization.

    Social bookmarking sites list

    ReplyDelete
  25. Your blog is very nice and we hope you are providing more information in future times.
    If any of you problem in your business you can contact to us.
    Legal Advisor

    ReplyDelete
  26. You have a great blog. this post in particular is very helpful! I know of a roofing company if you are interested in roofers seattle. Please get in touch! Thanks, have a good day.

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. Very nice, this is very good. i will share it to social media platform

    "A platform designed to provide Growers and Processors the opportunity to display and sell products to OMMA
    certified dispensaries and processors,
    Affordable pricing ensuring success for your business
    This site is FREE to all dispensaries to ensure maximum listings sales while giving them a better selection of products
    Oklahoma wholesale cannabis market place

    ReplyDelete
  29. I have read so many articles regarding the blogger lovers but this piece of writing is really a fastidious article, keep it up.

    ReplyDelete
  30. I have read so many articles regarding the blogger lovers but this piece of writing is really a fastidious article, keep it up.
    Cash for cars logan

    ReplyDelete
  31. Thanks, guys for sharing your valuable info. I really appreciate your efforts and I am definitely waiting for your next post thank you once again, Regards

    ReplyDelete
  32. I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it.
    Regards: Regards: cash for cars caboolture

    ReplyDelete

  33. Very nice, this is very good. i will share it to social media platform


    Whiten Your Teeth Faster
    With the Pearly Smile Teeth Whitening Kit you'll get whiter and brighter teeth, fast!
    best teeth whitening kit 2020

    ReplyDelete
  34. Really Interesting Blog. Thanks to share this useful content with us. I really like this post, and i learn lots of information through this blog.
    Thank you.
    If you want to learn How to Enable Java Plugin in Browser for Pogo Games so click and visit.

    ReplyDelete
  35. This comment has been removed by a blog administrator.

    ReplyDelete
  36. This comment has been removed by a blog administrator.

    ReplyDelete
  37. This comment has been removed by a blog administrator.

    ReplyDelete
  38. This comment has been removed by a blog administrator.

    ReplyDelete
  39. A plus article. Thanks for sharing this information.

    Chris
    Owner CEL Financial Services
    IRS Registered Tax Preparer
    Registered bonded California CTEC Tax Preparer
    https://incometaxprepfillmore.com

    ReplyDelete
  40. Thanks for your articles.Thanks for sharing useful resources with us. Visit now for Latest news bhairabnews.com

    ReplyDelete
  41. Thank you so much for the information that you have shared here with all of us. You have made it easier for us...

    Top online trainer

    ReplyDelete
  42. I am so amazed to get knowledge about asp.net here. I really located you by mistake, while I was searching about technical blogs related to Advanced Matching Facebook Pixel, Anyways I am here now and thanks for sharing such information.Please do keep up the great work.

    ReplyDelete
  43. Awesome job you have done through this article and all information is so amazing so thanks for sharing with us Visit lyricsforus

    ReplyDelete
  44. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative. outdoor media production house in pakistan

    ReplyDelete
  45. This is a wonderful beauty, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck. subtle signs he's not into you. beauty

    ReplyDelete
  46. Amazing. I have read so many articles in recent days regarding the blog & blogger lovers but this piece of writing is just wow.

    ReplyDelete
  47. Nice post i get inspired from this article and this is very interesting. oracle training in chennai

    ReplyDelete
  48. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts.

    Book Cheap Flight Tickets

    ReplyDelete
  49. Its very impressive blog, I like very much!!

    Online equity trading

    ReplyDelete
  50. Here is one of the best blog for correct and inresting information.
    Top Online Stock Broking

    ReplyDelete
  51. This can be a very informative and helpful post, very genuine and practical advice.

    professional web design services

    ReplyDelete
  52. This is best, Explained step by step and in a concise way.
    Thank you Goldcoders hyip templates

    ReplyDelete
  53. Thanks for posting this info. I just want to let you know that I just check out your site and I find it very interesting and informative. I can't wait to read lots of your posts.
    business directory

    ReplyDelete
  54. geat reading, i do a lot off Googlekomposit garden fencing panels

    ReplyDelete
  55. This post very good I just want to let you know that I just check out your site and I find it very interesting and informative.Amazan research

    ReplyDelete
  56. Thanks for sharing such huge content keep posting further
    concerts in lahore

    ReplyDelete
  57. I am really a big fan of your blogs, your blog is really awesome and I would like to say thank you to share such good information. I have started doing your tactics. Let’s see how it goes.

    https://khabreapki.com/

    ReplyDelete
  58. Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. 铭识协议

    ReplyDelete

  59. Awesome information i found here. I really admire to see your quality article. I will look forward to read your informative articles.


    Online Market Trading

    ReplyDelete
  60. This comment has been removed by the author.

    ReplyDelete
  61. Thankyou for this useful information.
    Visit Website - https://myblog-search.uk.com/norton-setup/

    ReplyDelete
  62. Wow This Article Help me alot and changed my life thank you so much admin for sharing your knowledge with us good job keep it up and please visit my Website

    ReplyDelete
  63. A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post.


    Happy Birthday Wishes

    ReplyDelete

  64. I really like your very well written post. it will be beneficial to everybody Keep it up.


    Custom Packaging Boxes with LOGO

    ReplyDelete
  65. Hi,

    Very nice article.

    I really enjoyed going through all the great information you’ve provided in this great article.

    Keep up the great work.

    Thank you
    How to choose credit card?

    What is the Credit card and the Advantages of Credit card?
    mortgage calculator

    ReplyDelete
  66. Hi,

    Very nice article.

    I really enjoyed going through all the great information you’ve provided in this great article.

    Keep up the great work.

    Thank you
    Sad Urdu Poetry

    ReplyDelete
  67. hey thanks for sharing this informative blog it is very helpful
    keep up the good work
    Anagha Engineers

    ReplyDelete
  68. Great article. The blog is covered by amazing content, thanks for sharing with us and keep updating! The Blog article is really excellent and unique. I will visit this blog again for this useful idea!
    WordPress Design Agency

    ReplyDelete
  69. I really like your very well written post. it will be beneficial to everybody Keep it up.


    Custom Packaging Boxes with LOGO

    ReplyDelete

  70. This is a very well presented post, my compliments. It has a lot of key elements that truly makes it work. And I love the outline and wordings. You really have a magnetic power that catches everyone in to your blog. Good one, and keep it going.
    Custom Packaging Box

    ReplyDelete

  71. A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post.


    Happy Birthday Wishes

    ReplyDelete
  72. I like the valuable info you provide in your articles. I will bookmark your blog and check again here frequently. Very useful info.

    Custom Box Printing

    ReplyDelete

  73. Your Post is very useful, I am truly happy to post my note on this blog . It helped me with ocean of awareness i really appreciate it.
    Asking.pk

    ReplyDelete

  74. Thanks for the nice blog. It was very useful for me.
    Custom Boxes Manufacturer

    ReplyDelete
  75. This is a best blog and full informative that helps us to design a bet packaging for our business
    Get Custom Boxes with

    ReplyDelete
  76. This is genuinely an awesome read for me. I have bookmarked it and I am anticipating perusing new articles. Keep doing awesome!
    Anagha Engineers

    ReplyDelete
  77. All I can say is great work. The effort you put into this is very impressive and I enjoyed every minute of the read. I hope to come back and see more articles you’ve written.
    Anagha Engineers

    ReplyDelete
  78. Great Technology News in Tamil from asmak9 blogger. Really it help me and saved a time

    ReplyDelete
  79. I like the article very much.And the article is quite informative.Thanks for a marvelous posting!
    Anagha Engineers

    ReplyDelete
  80. Hello there, I like your content, and really appreciate your efforts you put in the content. Keep publishing.
    CA Services Online

    ReplyDelete
  81. Thank you so much for sharing such valuable and intersting information
    Anagha Engineers

    ReplyDelete

  82. Thanks for sharing a Great post indeed. I am pleased by reading such a post like this
    Anagha Engineers

    ReplyDelete
  83. thanks for this post and information. nice

    ReplyDelete
  84. I am pleased by reading such a post like this.
    Anagha Engineers

    ReplyDelete
  85. Great Sharing thanks for sharing this valueable information…
    Anagha Engineers

    ReplyDelete
  86. Awesome post thank you sharing for knowledge.
    Anagha Engineers

    ReplyDelete
  87. Thanks for sharing the wonderful article, Helps a lot. Today I learn new things and try them in the future.
    Anagha Engineers

    ReplyDelete