How do I secure an API by only allowing trusted do

2019-06-01 18:56发布

问题:

Question

How do I secure an API by only allowing trusted domains?

Details

I am building a REST API. I need a way to distribute API Keys but only allow them to work from the domain they are registered with.

The main issue is my API Key needs to be embedded in a Flash File which can easily be decompiled to steal the API Key. If Flash makes this impossible I can use Javascript instead.

I have heard a lot of people say use $_SERVER['HTTP_REFERER']. But that is easily spoofed.

  • How do I build an API that makes sure a request is coming from an allowed domain?
  • How do I create an API key that is tied to a domain?
  • How do I secure an API by only allowing trusted domains?

Related Stackoverflow Questions:

These questions are related but didn't quite answer my question. Figured I would just put them here for future reference.

  • Google API Key and Domain Check
  • How does Google Maps secure their API Key? How to make something similar?

回答1:

JavaScript won't help you here - the problem is that the key is being stored on the client, which means that it is not secure. You can make it a bit more difficult for an attacker certainly (e.g. like you say checking the referrer), but at the end of the day all the server can verify is that the key is correct, and since the key can easily be stolen that's not very helpful.

The way this can be secured is by having the private keys run on the servers of whoever you are giving them to instead of in the client. Depending on your needs, this may not be feasible.

One possibility to make it a bit harder for attackers is to use the site-locking technique to only allow the SWF to call the API if it is on an appropriate domain. See http://blog.boogatech.com/as3_tutorial_site-locking_your_flash_project/ for an example. Please note however, that this is client security - the goal with sitelocking is usually just to stop people from playing your game on other sites (and even then it can't stop the most dedicated of attackers). In your case you are dealing with server security - the server doesn't know about the SWF, all it knows is the arguments it is being fed, so an attacker can just bypass the SWF and the client security and call the API from somewhere else.

I'd advise you to think about what attack and attackers you are trying to prevent (why do you have to tie API keys to a domain?). This will help you plan your security attempts better. For instance, if you are not running an ultra-critical API, you can decide that putting in a couple of things to make it harder for attackers to access the API is acceptable, with the knowledge that you can't stop an extremely dedicated attacker.