Is there a safe way to manage API keys?

前端 未结 4 1805
死守一世寂寞
死守一世寂寞 2020-12-07 09:18

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. I         


        
4条回答
  •  甜味超标
    2020-12-07 09:38

    Here is another way:

    Place the API key in a file accessible to the build machine/server, we'll call it:

    /usr/api_user/api_key1
    

    With contents:

    myApiKey = abcdefghijklmnopqrstuvwxyz
    

    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;
        /...
    }
    

    Then in your build.gradle, add something like this:

    buildConfigField "String", "MY_API_KEY", getMyApiKey("myApiKey")
    

    And also add this:

    //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) +"\""
    }
    

    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.

提交回复
热议问题