How to restrict direct calls to WebAPI – SharePoint 2013

Sathish Nadarajan
 
Solution Architect
October 19, 2015
 
Rate this article
 
Views
7151

In the previous articles, (WebAPI and Create WEBAPI) we saw how to create and call the WebAPI from our Javascripts in SharePoint 2013. Now, there is one more check, we need to do. i.e., while calling the WebAPI, from the Javascript, we would have given the WebAPI URL on the client Side. Hence, if some one who is having a knowledge of viewing the source, the end user will come to know the WebAPI. Obviously that is not a good practice. We expect the Users to access the WebAPI through our application. Not directly. So a validation needs to be done on the WebAPI.

 [HttpGet]
         public string MyMethod(string sampleParameter)
         {
             Uri urlReferrer = ((System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.UrlReferrer;
             if (urlReferrer != null)
             {
                 if (urlReferrer.AbsolutePath.ToLower().Contains("/sites/MySiteCollection") && urlReferrer. Host.ToLower().Contains(“MyDomain”))
                 {
 
                     // Do the actual stuff 
                      
                     return returnValue;
                 }
             }
             return "Not a Valid Request";
         }
 

Hence, on the above code, if the WebAPI is being called directly, the urlReferrer will not have our site collection url. Hence, the Method will return a “Not a valid Request” message.

When the request comes from our site collection, then only the web api will respond.

Though this looks very small, it is really important when considering the security.

Happy Coding,

Sathish Nadarajan.

Category : SharePoint, WebAPI

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment