且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 JavaScript 时如何保护 API 密钥?

更新时间:2022-06-22 00:20:34

简短回答:否

无论你做什么来混淆密钥,你仍然需要发送它以使其在客户端上可用,因此可以使用 fx 提取它.萤火虫.

What ever you do to obfuscate the key, you still have to send it to make it available on the client somehow, and therefore it will be possible to extract it using fx. Firebug.

即使你设计了一种神奇的方法来保密密钥,在某些时候你也必须发出实际的 API 请求,因为它必须从浏览器发送,攻击者将能够读取从 Firebugs 网络选项卡中以纯文本形式输出密钥.

Even if you devise an awesome magical way to keep the key secret, at some point you would have to make the actual API-request, and as it would have to be sent from the browser, an attacker would be able to read out the key in plain text from Firebugs net tab.

正确的做法是围绕需要密钥的 API 调用创建一个 PHP 包装器,然后从 Javascript 调用该包装器.

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.