如何使用外部 api 访问令牌而不将它们暴露给用户? [英] How to use external api access tokens without exposing them to the user?

查看:33
本文介绍了如何使用外部 api 访问令牌而不将它们暴露给用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Sorry if this might be a bit of a trivial question, but I wanna be sure and couldn't exactly find a definitive answer online.

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

I am writing a small app that uses Mapbox, and I am using react-map-gl for it. 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?

谢谢!

推荐答案

您无法避免在前端公开 API 密钥.如果有人想挖掘您的源代码,他们会找到它们.

You can't get away from revealing API keys on the front end. If someone wants to dig around in your source code, they will find them.

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

However, you should always configure any API key that is visible on the Internet to be restricted to specific referrers, i.e. the domain of your website.

这通常是在通过提供商的仪表板创建 API 密钥期间完成的.

Usually this is done during creation of an API key through your provider's dashboard.

对于 Mapbox,您可以阅读有关限制 API 令牌的文档 此处.它指出:

For Mapbox, you can read the documentation on restricting API tokens here. It states:

您可以通过添加 URL 限制使网络地图的访问令牌更加安全.当您向令牌添加 URL 限制时,该令牌仅适用于源自您指定的 URL 的请求.没有限制的令牌适用于源自任何 URL 的请求.

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.

(强调我自己的)

他们需要客户端的访问令牌,因此他们建议使用环境变量.我的问题是可以简单地在前端文件夹中创建一个 .env 文件并将变量放在那里吗?

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?

前端开发中使用环境变量有两个原因:

There are two reasons one uses environment variables in front-end development:

  1. 为方便起见,从源代码中删除特定于环境的配置.

  1. As a convenience, to keep environment-specific configuration removed from source code.

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

To keep sensitive information out of source code. You shouldn't commit API tokens or other similarly sensitive details to your version control.

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

Using environment variables in front-end code will not to keep their values secret from the end user. Whatever the value of an environment variable is at build time will be visible in the compiled output.

这篇关于如何使用外部 api 访问令牌而不将它们暴露给用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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