简体   繁体   English

使用 React、firebase 和 Github Action Deploy 时如何隐藏 API 密钥

[英]How to hide API keys when using React, firebase, and Github Action Deploy

I have a basic web application written in React that requires an API key to make requests.我有一个用 React 编写的基本 Web 应用程序,它需要一个 API 密钥来发出请求。 I want to be able to deploy my application on Firebase using Github Action Deploy (this I know how to do) and also be able to hide my API key.我希望能够使用 Github Action Deploy(我知道该怎么做)在 Firebase 上部署我的应用程序,并且还能够隐藏我的 API 密钥。 I have read many articles on hiding API keys in firebase but can't seem to figure out how to access them in react in a safe manner while also having the code base live on GitHub.我已经阅读了许多关于在 firebase 中隐藏 API 密钥的文章,但似乎无法弄清楚如何以安全的方式访问它们,同时将代码库放在 GitHub 上。

Well according to your comment, I think you want to store the API KEYS in the .env file and then you want to export them in your React app.根据您的评论,我认为您想将 API KEYS 存储在.env文件中,然后您想将它们导出到您的 React 应用程序中。

For .env.local file对于.env.local文件

  1. Create a .env.local file in your React source folder.在 React 源文件夹中创建一个.env.local文件。

反应文件夹

  1. Then put all of your API keys there, making sure that all of your API keys should start with REACT_APP_ (Like this 👇).然后把你所有的 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. And then you can get access to all these tokens in React by process.env .然后你可以通过process.env访问 React 中的所有这些令牌。 So your firebase.jsx file (or whatever you named) may look like this 👇.所以你的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. You can prevent .env.local from uploading to remote by adding it to the .gitignore file(which will be added by default to the .gitignore file provided by React).您可以通过将.env.local添加到.gitignore文件(默认情况下会添加到 React 提供的.gitignore文件)来阻止.env.local上传到远程。 .gitignore 文件

Hope it helps 🙌!希望对你有帮助🙌!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM