More Security Using Domain Filtering

February 16, 2017    node nodejs security tutorial es6

Most systems, if not all, need to use/does use some form of domain filtering for security. In my case, I needed to check against unauthorised usage from domains other than ones whitelisted by clients from their dashboard. This is definitely a necessity if your clients are going to be embedding your code into their sites. It keeps both parties safe from attacks.

The solution I came up with is pretty simple. We check the referrer domain sent to us from the client-side and check it against the array of whitelisted domains for a given user/client. We do not yet force our clients to use SSL or care about how they store their whitelisted domains with us, e.g. but they use www to access their site in the browser; so for now we ignore the protocol and additionally the www subdomain since the client side makes use of document.location.hostname to send to the server - document.location.hostname will only return the url without the protocol.

Assuming we have the user object on the server -


if ((user.whitelist.findIndex(domain => 
     domain.replace(/^(https?:\/\/)?(www\.)?/gi, '') === args.domain)) === -1) {
  return Promise.reject(new Error('Unauthorised domain'));

// continue execution

In the code above, we try to look up the index of the supplied domain by utilising the Array.prototype.findIndex function. Inside we return each individual domain minus the protocol and www subdomain, if any, and check it against the input. We also make sure to make the string replace global and case insensitive. If the index is equal to -1, then we immediately stop further execution and return an error.

comments powered by Disqus