Protecting Your Application from API Key Vulnerabilities
The easy and the right way to hide your API keys
Table of contents
Pushing your secret keys to GitHub can cause a security glitch on your application as people could use up your limited API calls or someone with malicious intent can gain access to your data. In this article, I'm going to show you probably the easiest way to hide your API keys.
Let's jump in
**1.Head over to the local.properties and add your API key **
api_access_key = "Your Key"
2. Add this lines to the root level of your app build.gradle
def localPropertiesFile = rootProject.file("local.properties")
def localProperties = new Properties()
localProperties.load(new FileInputStream(localPropertiesFile))
3. Add this line to the app-level build.gradle file
defaultConfig{
buildConfigField "String", "ACCESS_KEY", localProperties['api_access_key']
}
4. Sync Gradle and build project.
Example in Kotlin
interface NewsAPI {
companion object{
val api_key = BuildConfig.NEWS_API_KEY
}
5. Reference the key After successfully building you can reference your key
interface NewsAPI {
companion object{
val api_key = BuildConfig.NEWS_API_KEY
}
@GET("v2/top-headlines")
suspend fun getBreakingNews(
@Query("country") countryCode:String = "us",
@Query("page") pageNumber:Int = 1,
@Query("apiKey") apiKey:String = NewsAPI.api_key
): Response<NewsResponse>
@GET("v2/everything")
suspend fun searchNews(
@Query("q") searchQuery: String,
@Query("page") pageNumber: Int = 1,
@Query("apiKey") apiKey: String = NewsAPI.api_key
):Response<NewsResponse>
}
Your API keys are now secure and they will not be uploaded to Github.