问题描述
我在我的应用程序中使用 API.我目前从 java 接口管理 API 密钥
I am using an API within my app. I currently manage the API key from a java interface
public interface APIContract {
//The API KEY MUST NOT BE PUBLISH. It is possible to generate a new one for free from www.themoviedb.org
//Remove before commit !!!
String API_KEY = "abcdefghijklmnopqrstuvwxyz";
/...
}
这可以完成工作.我可以使用 APIContract.API_KEY
访问密钥,但正如您在评论中看到的那样,如果我使用 git 和公共存储库(我不打算发布此密钥),这是不安全的.
This do the job. I can access the key using APIContract.API_KEY
, but as you can see in the comment this is not safe if I use git and a public repository (I am not suppose to publish this key).
所以这是我的问题:是否可以将此密钥移动到另一个我可以从我的应用程序轻松访问但不会提交的地方?
So here is my question : is it possible to move this key in another place which I can easily access from my app but which will not be committed ?
我发现这个 线程使用 gradle 存储密钥,但我需要提交 build.gradle
文件,所以它不能完成这项工作.
I found this thread which use gradle to store the key, but I need to commit the build.gradle
file so it does not do the job.
有人知道如何解决这个问题吗?我在 stackoverflow 中没有发现类似的问题,但也许我错过了一些东西
Does someone know how to solve this problem ? I did not find similar problem in stackoverflow but maybe I missed something
编辑我喜欢将密钥移到任何 Java 代码之外的想法,因为其他人(可能是非技术人员)可以轻松管理他们自己的密钥.我正在考虑使用像 settings.gradle
这样的 gradle 文件.
EDIT
I love the idea of moving the key outside any java code because other people (maybe non technical people) can easily manage their own key. I was thinking about using a gradle file like settings.gradle
.
推荐答案
这是另一种方式:
将 API 密钥放在构建机器/服务器可访问的文件中,我们称之为:
Place the API key in a file accessible to the build machine/server, we'll call it:
/usr/api_user/api_key1
有内容:
myApiKey = abcdefghijklmnopqrstuvwxyz
您现在将使用 `BuildConfig' gradle 对象访问它.将您的代码修改为:
You will now access it using the `BuildConfig' gradle object. Modify your code to this:
public interface APIContract {
//The API KEY MUST NOT BE PUBLISH. It is possible to generate a new one for free from www.themoviedb.org
//Remove before commit !!!
String API_KEY = BuildConfig.MY_API_KEY;
/...
}
然后在你的 build.gradle 中,添加如下内容:
Then in your build.gradle, add something like this:
buildConfigField "String", "MY_API_KEY", getMyApiKey("myApiKey")
还要加上这个:
//return a MY API KEY from a properties file.
def getMyApiKey(String property){
Properties properties = new Properties()
properties.load(new FileInputStream("/usr/api_user/api_key1"))
return """ + properties.getProperty(property) +"""
}
如您所知,您可以重新定位 API 目录位置,使其不属于您的存储库.当然,然后它将具有构建的文件系统依赖项......您可以在 CI/CD 环境(可能是像 Jenkins 之类的工具)中设置一个列表,以将构建文件复制到私有存储库,以进行备份.
You can relocate the API directory location, as you can tell, so that it is not a part of your repo. Of course, then it will have file system dependencies for the build... which you could have a list setup in a CI/CD environment (maybe a tool like Jenkins) to replicate the build files to a private repo, for backup purposes.
这篇关于有没有一种安全的方法来管理 API 密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!