6

I've seen services like Google that require you add an API key when making a javascript call, like this.

https://www.google.com/jsapi?key=thekeygoeshere

What's the point of having this javascript api key when the code can be seen and the key can be read. Can't someone just copy this key and use it for their own site? Or is there something else that they do in the background to ensure that the key belongs to the site making the call?

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
zmol
  • 1,731
  • 5
  • 14
  • 14

2 Answers2

6

Presumably they check the referer HTTP header.

The majority of users send it. So if is:

  • The site that matches the key, they can operate as normal.
  • A site that doesn't match the key, they can reject the request.
  • Blank, they can operate as normal and allow a tiny fraction of people to use the API on the wrong site.

The majority of visitors to a site using the wrong key will get blocked, so it won't be worth using the wrong key on the site in the first place.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • That would be pretty risky, as the Referer-Header can be empty according to the standard (and it is for many users, as they don't want the website to know where they were before). – anroesti Feb 05 '11 at 14:11
  • Updated the answer explaining why it isn't really risky. – Quentin Feb 05 '11 at 14:20
  • This argument always comes up but if even 10% of users have it turned on (and I'm sure it's far greater) you would notice if a high traffic site was using your key. – ZoFreX Feb 05 '11 at 14:22
  • I'd be surprised if more than 0.5% had referer disabled. – Quentin Feb 05 '11 at 14:29
0

The google code will use AJAX or something similar that will make a call to their server detailing your key, and the url of the site it's being used on. Google can then check to see if its the correct site for that key and stop the code from working if not.

Although, the map API seems to work on any site with any key.

gunwin
  • 4,578
  • 5
  • 37
  • 59
  • As of v3, the map API no longer requires a key (unless you are using the premier service) – Matt Feb 05 '11 at 14:22