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, its detail can be studied here. 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.

64 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. With an end goal to decrease the measure of snaps expected to explore around a website, designers are utilizing lightboxes,top website designer in gurgaon overlays, extending and repositioned tiles, so as to stack however much substance as could reasonably be expected without really stacking another site page.

    ReplyDelete
  17. 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
  18. 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
  19. Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. freelance web designer

    ReplyDelete
  20. 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
  21. Then again, you can make due with the following best thing - Premium WordPress themes.premium wordpress blog themes

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

    ReplyDelete
  23. 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
  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 good article and thanks for sharing such information.


    Nanjing WUZUOJI Network Technology Co., Ltd
    Our company provides high-quality product suppliers for Amazon and eBay sellers,
    customizes products suitable for e-commerce sales from hundreds of factories in China,
    and supplies high-quality products such as clothing, electronic products,
    household goods and other e-commerce sellers for Amazon. Welcome your order

    ReplyDelete

  34. 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
  35. 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
  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. Very good article and thanks for sharing such information.


    Do you want to remove hair with ease, with no razor burn and no ingrown hairs?
    You now can from the comfort of your own home with little to no pain!
    GoneForever Laser Hair Removal Handset
    IPL Laser Hair Removal Handset

    ReplyDelete
  40. Very good article and thanks for sharing such information.

    Our 3D Showcase is an online experience for buyers to move through a property and see it from any angle. Our distinct tours give homebuyers a completely unique sense of the property.
    We bring listings to life with immersive ...

    experiences that are more than virtual tours. At Realty Show time our technology completely immerses visitors so they can create an emotional connection.

    We offer the latest real estate marketing technology to get more clients and sell more homes.

    If you've ever used Google Street View, you'll have a pretty good idea already of what Realty Show time presents. Using 3D imaging technology,

    Realty Show time allows online visitors to virtually "walk" through a property just like they would virtually "walk" around a city using Google Street View. This is the first piece of real estate technology that really allows users to control how the experience a property when they're looking at it online.

    "The key difference with this technology and what sets it apart from the videos and virtual tours that we are used to is that it allows the viewer a completely immersive, user-controlled walk around the experience of space in its entirety,"

    Get More info: Realty Show time

    Contact Info:

    Demetre Politis. Broker/Owner,

    email: djpolitis1@gmail.com.
    email: info@realtyshowtime.com

    Phone:

    Canada +14163009293
    Greece +306944043311


    website: Realty Show time

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

    ReplyDelete
  42. Thanks For Sharing ❤️ Also Visit Here for
    Premium Themes
    Here Is Some Premium Templates Lists You Can Download Free From Our Site
    Igniel Responsive Template
    Andro Store Responsive Template
    Arlina Responsive Template
    Novan Responsive Template

    ReplyDelete
  43. Wow. Thank you very much for sharing this informative and useful post. ❤️



    OUR MISSION

    We are a brokerage built on unrelenting dedication and authentic experience.

    Our ambition and enthusiasm for Real Estate have been a large factor in our brokerage’s success, however, it is the people that we are truly passionate about. Our mission is to provide you with the Real Estate of your dreams and that's what truly drives us forward.


    Demetre Politis Biography

    Award winning Real Estate professional Demetre Politis has over 26 years of experience selling Real Estate in the U.S. and Canada, Demetre now focuses in Greece and the rest of Europe with a vast knowledge of many areas and their differing realities.

    A dynamic individual, Demetre strongly believes in the potential of hard work and persistence. In 2015, he became the TOP PRODUCER in sales for Wrenwood Realty Inc. And in 2009, he became the recipient of the REMAX PLATINUM CLUB AWARD, recognized by the distinction amongst the TOP 1% IN REMAX in the industry. Additionally, Demetre is part of a select group of individuals in North America to have successfully completed the Leader's Edge Training. As he regularly participates in continuing education courses, Demetre is able to steadily upgrade and sharpen his expertise on the industry.

    An Broker/Agent with a true passion for Real Estate, Demetre chose the Real Estate industry over a career as a medical professional. After having graduated with honours in the Bachelor of Science and Bachelor of Science Pharmacy programs at the University of Toronto, Demetre shifted his career direction. His reason for delving into real estate was because it offered him the opportunity to explore what he loves most about homes: architecture, design, business and the art of selling. His passion has certainly lead him to success as Demetre reached the TOP 1% AT REMAX. Since then Demetre has opened his own brokerages, Realty Show Time and Wrenwood Realty and is now the Broker of Record/Owner of his own companies.

    Demetres’ approach to Real Estate is honest and integral, always putting the needs of his clients first. He truly enjoys getting out there and working with people to provide them with the perfect choice. As a result, a strong bond is often developed. His main mission has always been to create an environment of trust, respect and collaboration with his clients.



    Get More Information Realty Show Time

    Contact Info:

    Demetre Politis. Broker/Owne

    email: djpolitis1@gmail.com.
    email: info@realtyshowtime.com

    Phone: Canada +14163009293
    Greece +306944043311

    ReplyDelete
  44. 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
  45. Thanks for your articles.Thanks for sharing useful resources with us. Visit now for Latest news bhairabnews.com

    ReplyDelete
  46. 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
  47. 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
  48. Awesome job you have done through this article and all information is so amazing so thanks for sharing with us Visit lyricsforus

    ReplyDelete