DEV Community

Chandrasekar Kuppusamy
Chandrasekar Kuppusamy

Posted on • Originally published at Medium on

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

API keys exists everywhere! It’s common in all the 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, tons of time 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 life saver, git. Though it helped a lot to delete API Key from the previous commits in strings.xml using git-filter-branch, but what if the project has 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 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 like 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
Enter fullscreen mode Exit fullscreen mode

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

Click here to download the what your ward  — A social concern app built by ThoughtWorks to identify corportation wards in chennai.

Github link

Top comments (0)