Is there a safe way to manage API keys?

前端 未结 4 1801
死守一世寂寞
死守一世寂寞 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:19

    1. Store api keys in an xml file

    Put xml file "api_keys.xml" in the directory "res/values/".

    api_keys.xml

    
    
        XXXXX
    
    

    use api keys in java code

    context.getString(R.string.THE_MOVIE_DB_API_TOKEN);
    

    2. Store API keys with help of Gradle and the gradle.properties file

    Example_0 Example_1

    Add the following line to [USER_HOME]/.gradle/gradle.properties

    For Windows OS, an example for Denis user:

    C:\Users\Denis\.gradle
    

    gradle.properties

    MyTheMovieDBApiToken="XXXXX"
    

    Add the following code to the build.gradle file

    build.gradle

    apply plugin: 'com.android.application'
    
    android {
        ...
    
        defaultConfig {
            ...
        }
        buildTypes {
            release {
                ...
            }
        }
        buildTypes.each {
          it.buildConfigField 'String', 'THE_MOVIE_DB_API_TOKEN', MyTheMovieDBApiToken
        }
    }
    

    use api keys in java code

    BuildConfig.THE_MOVIE_DB_API_TOKEN)
    

    3. Store API keys with help of gradle and the system path variable

    Example_0

    Add new system PATH variable THE_MOVIE_DB_API_TOKEN="XXXXX":

    For Windows OS:

    • open system
    • advanced system settings
    • environment variables
    • add new variables to the user variables

    Add the following code to the build.gradle file

    build.gradle

    apply plugin: 'com.android.application'
    
    android {
        ...
    
        defaultConfig {
            ...
        }
        buildTypes {
            release {
                ...
            }
            buildTypes.each {
                it.buildConfigField 'String', 'THE_MOVIE_DB_API_TOKEN', "\"$System.env.THE_MOVIE_DB_API_TOKEN\""
            }
        }
    }
    

    use API keys in java code

    BuildConfig.THE_MOVIE_DB_API_TOKEN
    

    Link to my gist on github

提交回复
热议问题