How to restrict direct calls to WebAPI – SharePoint 2013


Sathish Nadarajan
SharePoint MVP
Published On :   19 Oct 2015
Visit Count
Today :  1    Total :   5456
Plan, Migrate, Secure, Report
SharePoint & Office 365 Tool. Simple & Easy to Use. 15-Day Trial!

SharePoint Office 365 Tool
Simple & Powerful Tool for Migration, Security & Reporting. Free Trial


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.

SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Categories

Migratiin Tools for SharePoint