如何在flutter中使用google secret管理

lsmepo6l  于 2023-02-25  发布在  Flutter
关注(0)|答案(1)|浏览(109)

我不想硬编码我的apis密钥和secret在代码中,为此我想使用google secret manager。为此我使用googleapis包。该包提供了一种访问google secret manager的方法。但我不知道如何使用它。如果有人能提供一个虚拟的示例代码和流程,这将是一个很大的帮助,我集成它。提前感谢

g9icjywg

g9icjywg1#

我就是这么做的。
首先,你需要从google cloud下载一个服务账户json,并将其存储在your assets文件夹中。

import 'dart:convert';
import 'package:flutter/services.dart';
import 'package:googleapis/secretmanager/v1.dart';
import 'package:googleapis_auth/auth_io.dart';
import 'package:http/http.dart' as http;

final String secretsPath = 'projects/$googleProjectId/secrets/$secretManagerName/versions/latest';

final credentials = json.decode(await rootBundle.loadString('assets/json/google-service-account.json'));

final AutoRefreshingAuthClient client = await clientViaServiceAccount(
        ServiceAccountCredentials.fromJson(credentials), [SecretManagerApi.cloudPlatformScope],
        baseClient: http.Client());

final SecretManagerApi api = SecretManagerApi(client);

Map<String, String> apiTokens = {};

final AccessSecretVersionResponse secrets = await api.projects.secrets.versions.access(secretsPath);

final String decoded = utf8.decode(base64Url.decode(secrets.payload!.data!));
    // the secrets are stored in a file where each line is a secret
final List<String> items = decoded.split('\n');
for (String line in items) {
    final List<String> data = line.split('=');
    if (data.length > 1) {
      apiTokens[data[0]] = data[1];
    }
}

相关问题