Securing API key in Android without pushing to remote repository (GIT)

API keys exist everywhere! It’s common in all modern apps! Isn’t it? So ever thought of securing it? Nope, I’d never done that before this post. I had done the same mistake committing to the repository and here are the hurdles that I had overcome.

We’re not a Time Machine :-)

Absolutely not, and there comes the lifesaver, git. Though it helped a lot to delete the API Key from the previous commits in strings.xml using git-filter-branch, what if the project has a bunch of branches and commits? and it is not a better idea to play with the code base.

Your code can be open-sourced, not your API key

Prevention is better than cure

Let’s cultivate the seeds at an early stage and secure our data using custom properties.

STEP 1: Create a file named secrets.properties in the main folder (i.e below local.properties, app, build, Gradle, README.md, etc.

STEP 2: Paste your API Key in secrets.properties (i.e GOOGLE_API_KEY, FACEBOOK_APP_ID, etc)

STEP 3: Sync the project or Rebuild.

STEP 4: Open build.gradle (app) and create a def function to access the key declared in the secrets.properties.

STEP 5: Create a variable for the function getApiKey() in defaultconfig using manifestPlaceholders to use it in AndroidManifest.xml

Hurray! You’re good to go. Now GOOGLE_MAPS_API_KEY variable is public and can be used in AndroidManifest.xml below

manifestPlaceholders — It helps to create a global variable that can be used only in AndroidManifest.xml

If you want to use it dynamically inside a Class, then add buildConfigField like

And, you can use GOOGLE_MAPS_API_KEY in Java or Kotlin classes like

BuildConfig.GOOGLE_MAPS_API_KEY

Finally, don’t forget to add secrets.properties to your .gitignore file.

Click here to download what your ward — A social concern app built by ThoughtWorks to identify corporation wards in Chennai.

Github link