如何在不向用户公开的情况下使用外部 api 访问令牌?

How to use external api access tokens without exposing them to the user?

抱歉,如果这可能是一个微不足道的问题,但我想确定并且无法在网上找到明确的答案。

我正在编写一个使用 Mapbox 的小应用程序,我正在为它使用 react-map-gl。他们需要客户端的访问令牌,因此他们建议使用环境变量。我的问题是是否可以在前端文件夹中简单地创建一个 .env 文件并将变量放在那里?

谢谢!

您无法避免在前端显示 API 键。如果有人想深入研究您的源代码,他们会找到的。

但是,您应该始终将在 Internet 上可见的任何 API 密钥配置为仅限于特定的引荐来源网址,即您网站的域。

通常这是在通过提供商的仪表板创建 API 密钥的过程中完成的。

对于 Mapbox,您可以阅读有关限制 API 个标记 here 的文档。它指出:

You can make your access tokens for web maps more secure by adding URL restrictions. When you add a URL restriction to a token, that token will only work for requests that originate from the URLs you specify. Tokens without restrictions will work for requests originating from any URL.

(强调我自己的)


They require the access token on the client side, so they suggest using an environment variable. My question is would it be okay to simply create a .env file in the front-end folder and put the variable there?

在 front-end 开发中使用环境变量有两个原因:

  1. 为方便起见,从源代码中删除 environment-specific 配置。

  2. 将敏感信息排除在源代码之外。您不应将 API 令牌或其他类似的敏感细节提交给您的版本控制。

在 front-end 代码中使用环境变量不会对最终用户保密它们的值。无论环境变量在构建时的值是什么,都将在编译输出中可见。