dart - 在 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
谢谢。
解决方案
要存储凭据等敏感信息,您应该使用 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
推荐阅读
- java - 如何处理java中的标志?
- python - 如何使用 matplotlib 在 python 中显示置信区间?
- scala - 使用 ScalaMock 时尝试模拟 DataFrameReader 对象时出错
- javascript - Twitter API 流式传输请求返回 401
- flutter - 如何重置 DragTarget 中的值?
- po - 使用 msgmerge 更新几个文件
- r - R 的 AzureKusto 库和对 Azure Log Analytics 的访问
- reactjs - 使用 react-testing-library 测试 MUI 复选框
- ios - MKGeoJSONDecoder 无法解析转义的双引号字符
- iis - IIS URL 将文件名的一部分重写为文件夹