[Android] API key 관리하기

강승구·2022년 5월 17일

API key를 숨겨야하는 이유

깃허브에는 모든 커밋과 리뷰는 기록이 남는다. 만약 API Key와 같은 중요한 정보들이 제대로 처리하지 않고 기록에 남는다면 민감한 정보들이 노출될 수 있기 때문에 주의해야한다.


API key 관리 방법

1. gitignore에 local.properties 추가

*.iml
.gradle
/local.properties
/.idea/caches
/.idea/libraries
/.idea/modules.xml
/.idea/workspace.xml
/.idea/navEditor.xml
/.idea/assetWizardSettings.xml
.DS_Store
/build <-
/captures
.externalNativeBuild
.cxx
// 추가
local.properties

2. local.properties에 api key 등록

## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file should *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
sdk.dir=/Users/kangseunggu/Library/Android/sdk
//API  KEY 추가
API_KEY = "api_key"

3. App 수준 gradle에서 BuildConfig에 API Key값 등록

import com.android.build.gradle.internal.cxx.configure.gradleLocalProperties

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
}

// local.properties 내부에서 key값을 가져오는 함수 구현
fun getApiKey(propertyKey: String): String {
    return gradleLocalProperties(rootDir).getProperty(propertyKey)
}

android {
    ...
    
    defaultConfig {
		...
        // key 가져오기
        buildConfigField("String", "API_KEY", getApiKey("API_KEY"))
    }

위 코드를 추가한 뒤 sync를 해주어야한다.

4. key값 사용하기

const val API_KEY = BuildConfig.API_KEY
profile
강승구

0개의 댓글