How to Hide an API Key in Client-Side Javascript

后端 未结 3 1608
有刺的猬
有刺的猬 2020-12-03 08:36

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 i

相关标签:
3条回答
  • 2020-12-03 08:44

    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

    0 讨论(0)
  • 2020-12-03 09:06

    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.

    0 讨论(0)
  • 2020-12-03 09:08

    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
    0 讨论(0)
提交回复
热议问题