使用 JavaScript 时如何保护 API 密钥?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11470389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to protect an API Key when using JavaScript?
提问by Roland
So, I'm developing a small application just for my own use and perhaps an open source project on Git. I'm using an API from Envato Marketplaces, and as you all know there are some operations that don't require any keys, but in the same time there are some that do require.
因此,我正在开发一个仅供我自己使用的小型应用程序,并且可能是一个关于 Git 的开源项目。我正在使用 Envato Marketplaces 的 API,众所周知,有些操作不需要任何密钥,但同时也有一些操作需要。
I first made a nice API wrapper for the Envato API in PHP, but then I decided to experiment a little bit with JavaScript, so I'm developing the same wrapper with JavaScript. So far I have no problems with the public operations, but I now have to use the API Key.
我首先用 PHP 为 Envato API 制作了一个很好的 API 包装器,但后来我决定用 JavaScript 做一些实验,所以我正在用 JavaScript 开发相同的包装器。到目前为止,我的公共操作没有问题,但我现在必须使用API Key。
My question would be if there's a way to protect the API Key in JavaScript. I cannot just put it there in plain text as it can then be used by others who see the code. So would there be an implementation where the API remains secret ? Maybe grabbing it from a JSON text file with XHR ?
我的问题是是否有办法保护 JavaScript 中的 API 密钥。我不能只是将它以纯文本形式放在那里,因为它可以被看到代码的其他人使用。那么会有一个 API 保持秘密的实现吗?也许用 XHR 从 JSON 文本文件中获取它?
采纳答案by AHM
Short answer: No
简短回答:否
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.
无论您做什么来混淆密钥,您仍然必须发送它以使其在客户端上可用,因此可以使用 fx 提取它。萤火虫。
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 请求,因为它必须从浏览器发送,攻击者将能够读出密钥Firebugs net 选项卡中的纯文本格式。
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.
正确的做法是围绕需要密钥的 API 调用创建一个 PHP 包装器,然后从 Javascript 调用该包装器。
回答by deRost
My solution right now is to write a little wrapper in rust, and throw it in the /cgi-bin and make calls to that. That should keep the api-key, api creds and session data separate from the client.
我现在的解决方案是用 rust 编写一个小包装器,然后将其放入 /cgi-bin 并调用它。这应该将 api-key、api creds 和 session 数据与客户端分开。