首页 > 解决方案 > 在 Flutter 应用程序中存储 API 凭据

问题描述

我在我的颤振应用程序中使用 googleapis 服务,它需要一些 JSON 格式的凭据。将此凭据存储在我的应用程序中的最佳方式是什么?

我可以在我的资产文件夹中保留一个 JSON 文件并在我的主函数中读取它吗?

或者我应该在我的主要功能中对凭据进行硬编码?我是颤振开发的新手。

我的代码如下所示

import 'package:googleapis/storage/v1.dart';
import 'package:googleapis_auth/auth_io.dart';

final _credentials = new ServiceAccountCredentials.fromJson(r'''
{
  "private_key_id": ...,
  "private_key": ...,
  "client_email": ...,
  "client_id": ...,
  "type": "service_account"
}
''');

const _SCOPES = const [StorageApi.DevstorageReadOnlyScope];

void main() {
  clientViaServiceAccount(_credentials, _SCOPES).then((http_client) {
    var storage = new StorageApi(http_client);
    storage.buckets.list('dart-on-cloud').then((buckets) {
      print("Received ${buckets.items.length} bucket names:");
      for (var file in buckets.items) {
        print(file.name);
      }
    });
  });
}

我应该在哪里保留以下凭据:

{
  "private_key_id": ...,
  "private_key": ...,
  "client_email": ...,
  "client_id": ...,
  "type": "service_account"
}

我不认为像上面这样的硬编码是一个好主意。

我认为这应该可行:https ://medium.com/@sokrato/storing-your-secret-keys-in-flutter-c0b9af1c0f69

谢谢。

标签: dartflutterflutter-dependencies

解决方案


要存储凭据等敏感信息,您应该使用 iOS 下的 Keychain 和 Android 下的 Keystore。

有一个完美的库,称为flutter_secure_storage.

以下是如何使用它:

// Create storage
final storage = new FlutterSecureStorage();

// Store password 
await storage.write(key: "password", value: "my-secret-password");

// Read value 
String myPassword = await storage.read(key: "password");

要使用它,请添加flutter_secure_storage: 3.2.1+1到您pubspec.yamlflutter packages get在终端中运行。

这是包和如何使用它的更详细的示例: https ://pub.dartlang.org/packages/flutter_secure_storage


推荐阅读