dart - 在 Flutter 应用程序中存储 API 凭据

标签 dart flutter flutter-dependencies

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

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

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

我的代码如下所示

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

谢谢。

最佳答案

要存储凭证等敏感信息,您应该使用 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.yaml 并在终端中运行 flutter packages get

这里是包和一个关于如何使用它的更详细的例子: https://pub.dartlang.org/packages/flutter_secure_storage

关于dart - 在 Flutter 应用程序中存储 API 凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55663207/

相关文章:

ios - Swift 的 Dispatchqueue 和 Flutter 的 Future 有什么区别?

dart - Dart Paper按钮onclick事件不起作用

flutter - 如何自定义 flutter 中的单选按钮?

ios - “此时无法安装此应用程序”错误 Xcode

flutter - 如何解决家庭酿造的 flutter 医生问题?

flutter - 如何让Flutter中的Alert Dialog在30秒后消失?

flutter - 如果我习惯用 Switch 小部件上的新 val 更改状态,如何使用函数回调?

ios - 如何将 Flutter 版本的 iOS 应用程序安装到我的 iPhone 上?

flutter - 不兼容的类型 : MainActivity cannot be converted to FlutterEngine, generatedPluginRegistrant.registerWith(this);

android - 失败 : Build failed with an exception (Flutter)