Making secure API calls to a mlab (Mongolab) sandbox

Posted on October 11th, 2015 at 05:00 PM


The free sandboxes at mlab are really useful for prototyping database services. Getting a db and queries up and running can be prototyped using a sandbox directly but for programmed access their REST API calls are really useful. For good reason mongolabs advise against direct API calls to their sandboxes due to exposure of your API key. The obvious security risk can be greatly reduced if you put the database call behind another service.

In our case we have called sandboxes from a WCF service. The consequential Cross-Origin Resource Sharing (CORS) conflict can be eliminated if you use a proxy from your host. For example see the C# code below;

using System.Net;
........
public const string MDApiKey = "apiKey=YOURMLABSAPIKEYSTRING";
public const string MDUrl = "https://api.mongolab.com/api/1/databases/";
public const string MDPath = "YOURDBNAME/collections/YOURCOLLECTIONNAME?";
........
query = "q={ \"key\" : \"" + keyvalue + "\" }";   // mongolabs query        

WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
webClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.6)" + 
    "Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)";
webClient.Headers.Add("referer", "http://YOURDOMAIN");
webClient.Proxy = new WebProxy("http://YOURISP-PROXY:YOURISP-PROXYPORT");
response = webClient.DownloadString(MDUrl + MDPath + query + "&" + MDApiKey);
webClient.Dispose();

// test if response == "[  ]" to determine if nothing returned from query