How to handle public API Keys?

Viewed 27

I see many APIs (e.g., stripe) that give both public and private keys to users; the former for front-end and the latter for back-end. How can you prevent someone from stealing/using the public (front-end) API keys? I've seen some people say you should have domain whitelisting, but those can be spoofed.

1 Answers

The point is that domains (origin) cannot be spoofed in a standard, unmodified browser. Sure, your api key can be used by others from non-browser clients, but what's the point, what would they gain, without your users' context? And they cannot use them in their own web project for their own users, because origin cannot be spoofed in a browser.

There is still some inherent risk (presented by attackers still being able to use these keys in non-browser clients), but there are usually also countermeasures on the providers' side to limit the impact of such abuse, and you should also design for this and always keep in mind that these keys are not actually secret. For example if the key is for client-side log collection, you must be aware that logs collected that way may not be authentic (can be forged by attackers), but they could also forge them on your website, because from their own browser they can send whatever they want.

Related