【问题标题】:How to hide API keys when using React, firebase, and Github Action Deploy使用 React、firebase 和 Github Action Deploy 时如何隐藏 API 密钥
【发布时间】:2021-09-09 21:21:10
【问题描述】:

我有一个用 React 编写的基本 Web 应用程序,它需要 API 密钥来发出请求。我希望能够使用 Github Action Deploy(我知道该怎么做)在 Firebase 上部署我的应用程序,并且还能够隐藏我的 API 密钥。我已经阅读了很多关于在 firebase 中隐藏 API 密钥的文章,但似乎无法弄清楚如何以安全的方式访问它们,同时将代码库放在 GitHub 上。

【问题讨论】:

  • 你不能。 React 应用程序在您用户的浏览器中运行,因此它不能直接使用您的密钥而不将其公开。
  • 如果您询问 Firebase 的配置数据(其中包含一个不幸命名为 apiKey 的密钥),请参阅:stackoverflow.com/questions/37482366/…
  • 有没有办法使用dotenv并将env变量存储在firebase中?

标签: reactjs firebase api github


【解决方案1】:

根据您的评论,我认为您希望将 API KEYS 存储在 .env 文件中,然后您希望将它们导出到您的 React 应用程序中。

对于.env.local 文件

  1. 在您的 React 源文件夹中创建一个 .env.local 文件。

  1. 然后将所有 API 密钥放在那里,确保所有 API 密钥都应以 REACT_APP_ 开头(像这样?)。
REACT_APP_apiKey="<your api key here which you copied from firebase>"
REACT_APP_authDomain="<your api key here which you copied from firebase>"
REACT_APP_projectId="<your api key here which you copied from firebase>"
REACT_APP_storageBucket="<your api key here which you copied from firebase>"
REACT_APP_messagingSenderId="<your api key here which you copied from firebase>"
REACT_APP_appId="<your api key here which you copied from firebase>"
REACT_APP_measurementId="<your api key here which you copied from firebase>"

  1. 然后您可以通过process.env 访问 React 中的所有这些令牌。因此,您的 firebase.jsx 文件(或您命名的任何文件)可能看起来像这样 ?。
const firebaseApp = firebase.initializeApp({
  apiKey: process.env.REACT_APP_apiKey,
  authDomain: process.env.REACT_APP_authDomain,
  projectId: process.env.REACT_APP_projectId,
  storageBucket: process.env.REACT_APP_storageBucket,
  messagingSenderId: process.env.REACT_APP_messagingSenderId,
  appId: process.env.REACT_APP_appId,
  measurementId: process.env.REACT_APP_measurementId,
});

// NOTE THE USE OF `process.env.REACT_APP_...`
  1. 您可以通过将.env.local 添加到.gitignore 文件(默认添加到React 提供的.gitignore 文件)来阻止.env.local 上传到远程。

希望对你有帮助?!

【讨论】:

    猜你喜欢
    • 2020-08-17
    • 1970-01-01
    • 2021-01-27
    • 2014-02-12
    • 2014-03-23
    • 1970-01-01
    • 2021-04-30
    • 2018-07-19
    相关资源
    最近更新 更多