At first, for MVP, I want to basically allow API requests to only come from my domains, or from a server-side script I control.

For the server-side script, I can simply use a "secret API token" sent in the Authorization Bearer header, and then check that on the API server.

But for the "public (non-secret) API token", which might be used from a public place like in a webpage in the browser (think how the Segment.com API uses a public key which you send from the browser, or how Google Analytics has a unique ID for your site, etc..), how do you verify that it comes from the specific website you gave the token to?

  • The Referer header can be spoofed, as can Origin, by a hacker's server-side script, so can't use those.
  • CORS only works because the browsers implement that, but a hacker's server-side script can ignore that.
  • Sending the public API key in the request, the hacker can just go into view-source in the browser, copy the public API key, and use it in their script, and set Referer and Origin to the site it got it from....

So is it even possible to verify the call came from my domain, and not a hacker's script? If so, what is the general approach?

1 Answer 1


So is it even possible to verify the call came from my domain, and not a hacker's script?

No. First of all, calls don't come from domains. Calls come from machines connected to the Internet. And there is no way to prevent a hacker from copying any request byte by byte. Hackers won't use browsers to do that. Why would they? Browsers only limit them. So, regardless of what piece of information you look at, a hacker can copy it ideally.

If so, what is the general approach?

The best solution is to accept that hackers will be able to access your server and be prepared for that.

Then, you can actually look at the Referer and Origin headers. Because the overwhelming majority of users are not hackers, you can still use this information to your advantage. Just don't assume you will block everyone; that won't happen.

It is a similar situation to User-Agent header. Hackers can forge it however they want. However, most users are not hackers, so we still utilize this information.

Of course, depending on what you are trying to do, you may want to look at other factors. Like IP, some behaviours are hard to reproduce (e.g., passing some random but not really random data to the server), etc. which will help you analyze who is a hacker and who is not. That would be useful if you are writing security software. But it will still be possible to hack you and the effort is unlikely to be worth it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .