views:

159

answers:

1

I have a JSON web service that I only want to provide for certain sites. It's a service that would be called through JavaScript using JSONP. How would I go about preventing (or at best making it more difficult for) unauthorized sites from accessing it? Requiring a user/password won't work because that would be plainly visible in JavaScript.

Example: My web service at domain.com provides weather information, and I only want website.com and webpage.com to be able to access it. But since the web service is accessed through JavaScript, lazywebsite.com could just view website/webpage's source and copy/paste their JavaScript code.

My thoughts so far:

  • Use an API key and log the HTTP_REFERER of where the service is accessed from. This isn't ideal since HTTP_REFERER is unreliable.
  • Have website.com/webpage.com generate a unique key server-side using an algorithm that I provide, save it in a session, and use that as a key to access the web service. This way, the token is only registered for that specific visitor and the JS can't be copy/pasted. The problem then shifts to website.com/webpage.com protecting their page that generates the unique key.

Are there any better solutions?

+2  A: 

There's no perfect way.

If you're serious about security, the solution is to not publish your JSON service to the world. Make it private and require website.com and webpage.com to make a private, backend request from their servers to yours for the data. Then you can authenticate all you want and the secrets stay safe in their server code. Basically it's a proxy solution. (One nice advantage: your JSON data will now have the same origin as the website, meaning you don't have to do JSONP hacks).

If you're less serious about security and just want to make it difficult, the simplest things you've already laid out. Check Referer. That header can be spoofed, but it's a pain and hopefully most attackers won't think to try it. Also require a password and/or API-key (they're equivalent), and obfuscate it inside the Javascript to make it harder to get at.

Nelson