使用带有 github 操作的 flutter web 时如何访问机密 步骤如下

问题描述

我有一个 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 文件而在源代码管理中被忽略。

步骤如下

  1. 在您的本地机器上,使用 base64 命令对 secrets.dart 的内容进行编码:
      base64 lib/path/to/secrets.dart
    
  2. 将输出复制并粘贴到您的 GitHub 密钥中,将其命名为 $SECRETS_FILE_CONTENT 或任何您想要的名称。
  3. flutter pub get 步骤之前将此 CI 步骤添加到您的 yaml 脚本中。
      # 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 ...
    

编辑

当人们使用 firebase 时,这也是隐藏 google-services.json 的相同过程。或者使用签名密钥(key.jkskey.keystore)。