title: Protecting a JSON Web Service
body: <p>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.</p>
  
  <p>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.</p>
  
  <p>My thoughts so far:</p>
  
  <ul>
  <li>Use an API key and log the <code>HTTP_REFERER</code> of where the service is accessed from.  This isn't ideal since <code>HTTP_REFERER</code> is unreliable.</li>
  <li>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.</li>
  </ul>
  
  <p>Are there any better solutions?</p>