简体   繁体   中英

How to Hide an API Key in Client-Side Javascript

Right now I am writing a client-side javascript app that makes a request to the USPS Price Calculator API. In order to make this request, I need to provide my API User ID in the xml of the request. The tag looks like this: <RateV4Request USERID="ThisIsWhereMyUserIdGoes"> . My question is this: is there any way I can provide my user ID to the javascript, while still hiding it from users who look at the client-side files. Right now, the only solution I have is to create a PHP file in my server that has the User ID, then using an AJAX request in the client-side javascript to store it in a global variable. It looks like this:

var userID;
$.get("/secrets.php", function( data ) { 
       userID = data;
});

Is this an adequate way of keeping my API User ID from being seen by the users of my app? What else could I do?

In short: No, you can't secure your API key in a client-side app.

This article goes into some more detail

Two options

  • Make the API calls server-side and then serve information to the client from there
  • Require the client use their own API keys

Even with your PHP solution you can't hide your userId. It can be easily printed in browser console by accessing consle.log(userId); . As far as I know anything that is available to client-side is vulnerable and can easily be decoded. Even if you obfuscate your api key it can still be decoded from clientside.

The right thing to do is to create a PHP wrapper around the API calls that require keys, and then call that wrapper from Javascript.

If you are reading this page in 2020 and don't want to develop server-side code for whatever reasons(saving hosting cost, etc), severless function might be the solution.

This also calls 3rd party API from the server-side, but you don't have to develop a full-fledged server-side API proxy.

Netlify has documentation on this. I guess other providers like AWS lambda, Google cloud function offers similar things but not sure.

https://github.com/netlify/code-examples/tree/master/function_examples/token-hider

Pros No server management

Cons Vendor lock-in

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM