問題描述
我在我的應用程序中使用 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 密鑰?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!