Hide and Keep your API key out of GitHub repository
![]() |
Secure your API key |
When you upload your Android app on GitHub, you need to hide it as no one has access to it except you. It is considered a security glitch, so that’s why it is important to hide your API key. I am going to show you how you can do that easily.
Some Developers store their API key in a String variable like this.
private static final String APK_KEY = "asjsdakf4d3ggs2ytm4x";
It is not good to push your secret things into public repository as other people could use up your limited API calls. That’s probably the least concerning situation. Sharing of API keys becomes more of a concern if the API key authenticates someone for access to a subset of data.
So, let’s see how we can do that.
1. Create a file called gradle.properties in .gradle folder.
- Drive C
- Users folder
- your user folder
- .gradle folder
Create it here
- gradle.properties
Then, write your APPNAME_API_KEY = "asjsdakf4d3ggs2ytm4x" inside it.
Save it as PROPERTIES File by enclosing with double quotes like this "gradle.properties"
2. Next step, Go to module level build.gradle file in your project
Then, put your API key for debug and release purposes under buildTypes tree.
buildConfigField ‘String’, “ApiKey”, APPNAME_API_KEY
It will be like that
buildTypes { debug{ buildConfigField 'String', "ApiKey", APPNAME_API_KEY } release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' buildConfigField 'String', "ApiKey", APPNAME_API_KEY } }
Sync it
3. Last Step, access your APK key in your Java file like that
private static final String API_KEY = BuildConfig.ApiKey;
If ApiKey goes red, press Make Project button or use Ctrl+F9
Another Way to do that:
1. Add the API key to your local.properties file:
apiKey="Your Key"
def localProperties = new Properties() localProperties.load(new FileInputStream(rootProject.file("local.properties")))
android { defaultConfig { // ... buildConfigField "String", "API_KEY",localProperties['apiKey'] } }
4. Sync Gradle and build the project. You can now reference the key:
String apiKey = BuildConfig.API_KEY;
Sounds pretty easy, does it?. Whenever you upload your Android project on GitHub, the person that uses your repository will not be able to figure out what your API key is. Therefore, you are secure NOW.
Comments
Post a Comment