I am writing an app that uses a 3rd party API service (say Google Maps, segment-analytics etc...). All these apps give an API key that is supposed to be embedded in the JS code.
So anyone who can inspect the source knows the client key. How do these services prevent wrongful usage of that key. Say someone calls these APIs with my key as many times as the daily allowed maximum API call limit, which will make the further actual API calls fail.
I know that Referrer Header can be used to check the request origin, but Referrer Header can be easily spoofed by a savvy user.
I don't know if there are any measures taken by the services. Seems like a very major problem.
Thanks in advance.
It is a risk, but it's not as bad as it may seem if the API provider is prepared.
The first thing to note is that such an API key is not used for authentication in the sense that it does not authenticate the caller (neither the application nor the enduser). It is only for things like rate limiting and tracking.
So really threats are similar to what you described, for example somebody using your API key and using up your quota. However, if that person is doing that from his own computer or network, all the malicious traffic is seen from his IP or IP range. If the API provider is smart and has good monitoring (like Google), they will not revoke/disable your API key but will filter or disregard the malicious traffic only.
So the attacker should be able to put up a website using your API key and get users to visit it. However, in this case the referer/origin headers cannot be spoofed, browsers won't normally allow Javascript to change the referer or the origin header in the request. So again, the API provider has a way to filter malicious traffic based on referer/origin.
The attacker would need access to many different clients, something like a botnet to make all those requests with your API key to use up your quota. This would probably work, but if an attacker can attack your site with distributed denial of service, your primary concern will probably not be your API keys.