遵循最佳做法,正确地将API密钥存储在抖动中 [英] Correct way of storing API Keys in flutter following best practises
问题描述
在我想在github上推送代码的情况下,在Flutter中添加秘密API密钥的正确方法(最佳实践)是正确的。我制作了一个使用API的简单应用程序,但是我以粗鲁的方式使用了该密钥,只是为了测试该应用程序是否正常运行。通常,根据我在后端开发应用程序的经验,密钥存储在某个位置和其他文件中,然后只需将其导入到需要 API_KEY
的所需文件中,并排除 .gitignore
文件中的文件。
Which is the correct way(best practice) of adding secret API keys in flutter in case I want to push the code on github. I've made a simple app that consumes an API but I used the key in a crud way just to test whether the app is working. Usually from my experience developing applications in the back-end, Keys are stored somewhere and in different file then one would simply import it to the required file that needs the API_KEY
and exclude the file in .gitignore
file.
到目前为止,我还实现了这种方法:
So far I have also implemented this approach:
-lib
-auth
-keys.dart
-secrets.json
secrets.json
在这里我将添加 KEY
并在
secrets.json
This is where I will add the KEY
and specify this file in .gitignore
to be excluded from being added in github when I push my code.
//Add API KEY HERE
{
"api_key": "ee4444444a095fc613c5189b2"
}
keys.dart
keys.dart
import 'dart:async' show Future;
import 'dart:convert' show json;
import 'package:flutter/services.dart' show rootBundle;
class Secret {
final String apikey;
Secret({this.apikey=""});
factory Secret.fromJson(Map<String, dynamic>jsonMap){
return new Secret(apikey:jsonMap["api_key"]);
}
}
class SecretLoader {
final String secretPath;
SecretLoader({this.secretPath});
Future<Secret> load() {
return rootBundle.loadStructuredData<Secret>(this.secretPath,
(jsonStr) async {
final secret = Secret.fromJson(json.decode(jsonStr));
return secret;
});
}
}
我觉得这种方法太多了。我希望获得更好方法的建议。
I feel like this approach is too much. I would like to get suggestions of a better approach.
推荐答案
编辑:在下面查看J. Saw的评论
Look at J. Saw's comment below
使用 Firebase远程配置
。在Firebase控制台的菜单内,向下滚动到 Grow
,然后再滚动到 Remote Config
。您可以在此处添加带有值的参数。完成后,别忘了发布更改。
Use Firebase Remote Config
. Inside the Firebase console, inside the menu, scroll down to Grow
and then Remote Config
. Here you can add a parameter with a value. When you're done don't forget to publish the changes. It's kind of subtle.
现在安装<用于Flutter的href = https://pub.dev/packages/firebase_remote_config rel = nofollow noreferrer> firebase_remote_config 。
导入所有内容后,您可以使用以下代码检索值:
After importing everything, you can retrieve your value using this code:
RemoteConfig remoteConfig = await RemoteConfig.instance;
await remoteConfig.fetch(expiration: Duration(hours: 1));
await remoteConfig.activateFetched();
remoteConfig.getValue('key').asString();
这样,API密钥或令牌就不再属于您的应用程序。
This way, the API key or token is never part of your application.
注意::当前存在问题,您会收到一条警告,指出未设置应用程序的名称,但这不会影响功能。
Note: there is currently an issue where you get a warning stating the application's name is not set, but this won't affect functionality.
这篇关于遵循最佳做法,正确地将API密钥存储在抖动中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!