使用 JavaScript 时如何保护 API 密钥? [英] How to protect an API Key when using JavaScript?

查看:46
本文介绍了使用 JavaScript 时如何保护 API 密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我正在开发一个仅供我自己使用的小型应用程序,并且可能是一个关于 Git 的开源项目.我使用的是 Envato Marketplaces 的 API,众所周知,有些操作不需要任何密钥,但同时也有一些操作需要.

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.

我首先用 PHP 为 Envato API 制作了一个很好的 API 包装器,但后来我决定用 JavaScript 做一些实验,所以我正在用 JavaScript 开发相同的包装器.到目前为止,我的公共操作没有问题,但我现在必须使用API​​ Key.

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.

我的问题是是否有办法保护 JavaScript 中的 API 密钥.我不能只是将它以纯文本形式放在那里,因为它可以被看到代码的其他人使用.那么会有一个 API 保持秘密的实现吗?也许用 XHR 从 JSON 文本文件中抓取它?

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 ?

推荐答案

简短回答:否

无论你做什么来混淆密钥,你仍然需要发送它以使其在客户端上可用,因此可以使用 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.

这篇关于使用 JavaScript 时如何保护 API 密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆