使用带有github操作的flutterweb时如何访问机密
我有一个flutter web应用程序,为了访问数据库,我在secrets.dart文件中硬编码了一个APIKey ,这工作得很好。我已将此文件添加到.gitignore以防止它推送到版本控制。但是当涉及到使用 GitHub 操作部署应用程序时,脚本失败,因为它没有检测到机密文件。
我确实从 Github上查看了关于Encrypted secrets的文档,它基本上允许存储机密。但似乎这些机密只能在 yml 文件中访问。
我想知道如何在我的应用程序中使用这个秘密,以便我的脚本成功运行并部署应用程序。这是我的文件夹结构
lib/
services/
database.dart /// this file uses the APIkey from secrets.dart
secrets.dart /// contains the APIkey
我能想到的解决这个问题的一种方法是使用.env文件,但我不太熟悉如何通过 CI 脚本在 .env 文件中添加密钥。我相信这也能解决我的问题。
这是我的 CI 脚本
# This file was auto-generated by the Firebase CLI
# https://github.com/firebase/firebase-tools
name: Deploy to Firebase Hosting on merge
"on":
push:
branches:
- master
jobs:
build_and_deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-java@v1
with:
java-version: "12.x"
- uses: subosito/flutter-action@v1
with:
channel: "master"
- run: flutter pub get
- run: flutter pub run build_runner build --delete-conflicting-outputs
- run: flutter build web --release
- uses: FirebaseExtended/action-hosting-deploy@v0
with:
repoToken: "${{ secrets.GITHUB_TOKEN }}"
firebaseServiceAccount: "${{ secrets.FIREBASE_SERVICE_ACCOUNT_VOCABHUB_34C7F }}"
channelId: live
projectId: vocabhub-34c7f
env:
FIREBASE_CLI_PREVIEWS: hostingchannels
回答
您可以secrets.dart在源代码管理中被忽略的同时使用您的文件。
以下是步骤
- 在您的本地机器上,
secrets.dart使用base64命令对您的内容进行编码:base64 lib/path/to/secrets.dart - 将输出复制并粘贴到您的 GitHub 机密中,为其命名
$SECRETS_FILE_CONTENT或任何您想要的名称。 - 将此 CI 步骤添加到该步骤之前的yaml脚本中
flutter pub get。# other stuff ... - run: echo $SECRETS_FILE_CONTENT | base64 -d > lib/path/to/secrets.dart env: SECRETS_FILE_CONTENT: ${{ secrets.SECRETS_FILE_CONTENT }} - run: flutter pub get - run: flutter pub run build_runner build --delete-conflicting-outputs - run: flutter build web --release # other stuff ...
要在 GitHub 用户界面中添加密钥,请按照下列步骤操作:
你的秘密应该出现在 UI 的下层“存储库秘密”中,它不应该出现在“环境秘密”中,因为那些不适用于简单的${{ secrets.name_of_variable }}.
为了提供更多上下文,您的存储库中的“操作”文件(例如 .github/workflows/ci.yml)应如下所示:
name: CI
on:
push:
branches: [ main, dev ]
pull_request:
branches: [ main ]
# Allows to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Decode base64 secrets
run: echo $SECRETS_FILE_CONTENTS | base64 -d > lib/path/to/secrets.dart
env:
SECRETS_FILE_CONTENTS: ${{ secrets.SECRETS_FILE_CONTENTS }}
# … put your steps here
- name: Do stuff
run: flutter pub get
编辑
google-services.json当人们使用 firebase 进行隐藏时,这也是相同的过程。或者使用签名密钥(key.jks或key.keystore)。