많은 사용자가 새 Android 지원 기기를 설정할 때 여전히 자신의 사용자 인증 정보를 직접 관리합니다. 이 수동 프로세스는 어려울 수 있으며 사용자 환경이 저하되는 경우가 많습니다. Google Play 서비스에서 제공하는 라이브러리인 Block Store API는 사용자 비밀번호를 저장할 때 발생하는 복잡성이나 보안 위험 없이 앱에서 사용자 인증 정보를 저장할 수 있는 방법을 제공하여 이 문제를 해결합니다.
Block Store API를 사용하면 앱에서 데이터를 저장하고 나중에 이 데이터를 검색하여 새 기기에서 사용자를 다시 인증할 수 있습니다. 이렇게 하면 사용자가 새 기기에서 앱을 처음 실행할 때 로그인 화면을 볼 필요가 없으므로 더 원활한 환경을 제공할 수 있습니다.
블록 저장소를 사용하면 다음과 같은 이점이 있습니다.
- 개발자를 위한 암호화된 사용자 인증 정보 저장소 솔루션입니다. 사용자 인증 정보는 가능한 경우 엔드 투 엔드 암호화됩니다.
- 사용자 이름과 비밀번호 대신 토큰을 저장합니다.
- 로그인 과정에서 발생하는 불편을 제거합니다.
- 사용자가 복잡한 비밀번호를 관리하는 부담을 덜어줍니다.
- Google에서 사용자의 신원을 확인합니다.
시작하기 전에
앱을 준비하려면 다음 섹션의 단계를 완료하세요.
앱 구성
프로젝트 수준의 build.gradle 파일에서 Google의 Maven 저장소를 buildscript 및 allprojects 섹션에 포함합니다.
buildscript {
repositories {
google()
mavenCentral()
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
모듈의 Gradle 빌드 파일(일반적으로 app/build.gradle임)에 Block Store API의 Google Play 서비스 종속 항목을 추가합니다.
dependencies {
implementation 'com.google.android.gms:play-services-auth-blockstore:16.4.0'
}
작동 방식
블록 스토어를 사용하면 개발자가 최대 16바이트 배열을 저장하고 복원할 수 있습니다. 이를 통해 현재 사용자 세션과 관련된 중요한 정보를 저장할 수 있으며 원하는 방식으로 이 정보를 저장할 수 있는 유연성을 제공합니다. 이 데이터는 엔드 투 엔드 암호화될 수 있으며 Block Store를 지원하는 인프라는 백업 및 복원 인프라를 기반으로 빌드됩니다.
이 가이드에서는 사용자의 토큰을 Block Store에 저장하는 사용 사례를 다룹니다. 다음 단계에서는 Block Store를 활용하는 앱의 작동 방식을 간략하게 설명합니다.
- 앱의 인증 흐름 중에 또는 그 이후 언제든지 사용자의 인증 토큰을 Block Store에 저장하여 나중에 검색할 수 있습니다.
- 토큰은 로컬에 저장되며 클라우드에 백업할 수도 있고, 가능한 경우 엔드 투 엔드 암호화됩니다.
- 사용자가 새 기기에서 복원 흐름을 시작하면 데이터가 전송됩니다.
- 사용자가 복원 흐름 중에 앱을 복원하면 앱은 새 기기의 블록 스토어에서 저장된 토큰을 가져올 수 있습니다.
토큰 저장
사용자가 앱에 로그인하면 해당 사용자를 위해 생성한 인증 토큰을 Block Store에 저장할 수 있습니다. 항목당 최대 4KB의 고유 키 쌍 값을 사용하여 이 토큰을 저장할 수 있습니다. 토큰을 저장하려면 StoreBytesData.Builder 인스턴스에서 setBytes() 및 setKey()를 호출하여 사용자의 사용자 인증 정보를 소스 기기에 저장합니다. Block Store를 사용하여 토큰을 저장하면 토큰이 암호화되어 기기에 로컬로 저장됩니다.
다음 샘플은 인증 토큰을 로컬 기기에 저장하는 방법을 보여줍니다.
자바
BlockstoreClient client = Blockstore.getClient(this);
byte[] bytes1 = new byte[] { 1, 2, 3, 4 }; // Store one data block.
String key1 = "com.example.app.key1";
StoreBytesData storeRequest1 = StoreBytesData.Builder()
.setBytes(bytes1)
// Call this method to set the key-value pair the data should be associated with.
.setKeys(Arrays.asList(key1))
.build();
client.storeBytes(storeRequest1)
.addOnSuccessListener(result -> Log.d(TAG, "stored " + result + " bytes"))
.addOnFailureListener(e -> Log.e(TAG, "Failed to store bytes", e));
Kotlin
val client = Blockstore.getClient(this)
val bytes1 = byteArrayOf(1, 2, 3, 4) // Store one data block.
val key1 = "com.example.app.key1"
val storeRequest1 = StoreBytesData.Builder()
.setBytes(bytes1) // Call this method to set the key value with which the data should be associated with.
.setKeys(Arrays.asList(key1))
.build()
client.storeBytes(storeRequest1)
.addOnSuccessListener { result: Int ->
Log.d(TAG,
"Stored $result bytes")
}
.addOnFailureListener { e ->
Log.e(TAG, "Failed to store bytes", e)
}
기본 토큰 사용
키 없이 StoreBytes를 사용하여 저장된 데이터는 기본 키 BlockstoreClient.DEFAULT_BYTES_DATA_KEY를 사용합니다.
자바
BlockstoreClient client = Blockstore.getClient(this);
// The default key BlockstoreClient.DEFAULT_BYTES_DATA_KEY.
byte[] bytes = new byte[] { 9, 10 };
StoreBytesData storeRequest = StoreBytesData.Builder()
.setBytes(bytes)
.build();
client.storeBytes(storeRequest)
.addOnSuccessListener(result -> Log.d(TAG, "stored " + result + " bytes"))
.addOnFailureListener(e -> Log.e(TAG, "Failed to store bytes", e));
Kotlin
val client = Blockstore.getClient(this);
// the default key BlockstoreClient.DEFAULT_BYTES_DATA_KEY.
val bytes = byteArrayOf(1, 2, 3, 4)
val storeRequest = StoreBytesData.Builder()
.setBytes(bytes)
.build();
client.storeBytes(storeRequest)
.addOnSuccessListener { result: Int ->
Log.d(TAG,
"stored $result bytes")
}
.addOnFailureListener { e ->
Log.e(TAG, "Failed to store bytes", e)
}
토큰 검색
나중에 사용자가 새 기기에서 복원 흐름을 진행하면 Google Play 서비스는 먼저 사용자를 인증한 다음 블록 스토어 데이터를 가져옵니다. 사용자는 복원 흐름의 일부로 앱 데이터를 복원하는 데 이미 동의했으므로 추가 동의가 필요하지 않습니다. 사용자가 앱을 열면 retrieveBytes()를 호출하여 Block Store에서 토큰을 요청할 수 있습니다. 그런 다음 검색된 토큰을 사용하여 새 기기에서 사용자를 로그인 상태로 유지할 수 있습니다.
다음 샘플은 특정 키를 기반으로 여러 토큰을 검색하는 방법을 보여줍니다.
자바
BlockstoreClient client = Blockstore.getClient(this);
// Retrieve data associated with certain keys.
String key1 = "com.example.app.key1";
String key2 = "com.example.app.key2";
String key3 = BlockstoreClient.DEFAULT_BYTES_DATA_KEY; // Used to retrieve data stored without a key
List<String> requestedKeys = Arrays.asList(key1, key2, key3); // Add keys to array
RetrieveBytesRequest retrieveRequest = new RetrieveBytesRequest.Builder()
.setKeys(requestedKeys)
.build();
client.retrieveBytes(retrieveRequest)
.addOnSuccessListener(
result -> {
Map<String, BlockstoreData> blockstoreDataMap = result.getBlockstoreDataMap();
for (Map.Entry<String, BlockstoreData> entry : blockstoreDataMap.entrySet()) {
Log.d(TAG, String.format(
"Retrieved bytes %s associated with key %s.",
new String(entry.getValue().getBytes()), entry.getKey()));
}
})
.addOnFailureListener(e -> Log.e(TAG, "Failed to store bytes", e));
Kotlin
val client = Blockstore.getClient(this)
// Retrieve data associated with certain keys.
val key1 = "com.example.app.key1"
val key2 = "com.example.app.key2"
val key3 = BlockstoreClient.DEFAULT_BYTES_DATA_KEY // Used to retrieve data stored without a key
val requestedKeys = Arrays.asList(key1, key2, key3) // Add keys to array
val retrieveRequest = RetrieveBytesRequest.Builder()
.setKeys(requestedKeys)
.build()
client.retrieveBytes(retrieveRequest)
.addOnSuccessListener { result: RetrieveBytesResponse ->
val blockstoreDataMap =
result.blockstoreDataMap
for ((key, value) in blockstoreDataMap) {
Log.d(ContentValues.TAG, String.format(
"Retrieved bytes %s associated with key %s.",
String(value.bytes), key))
}
}
.addOnFailureListener { e: Exception? ->
Log.e(ContentValues.TAG,
"Failed to store bytes",
e)
}
모든 토큰을 검색합니다.
다음 예에서는 BlockStore에 저장된 모든 토큰을 검색하는 방법을 보여줍니다.
자바
BlockstoreClient client = Blockstore.getClient(this)
// Retrieve all data.
RetrieveBytesRequest retrieveRequest = new RetrieveBytesRequest.Builder()
.setRetrieveAll(true)
.build();
client.retrieveBytes(retrieveRequest)
.addOnSuccessListener(
result -> {
Map<String, BlockstoreData> blockstoreDataMap = result.getBlockstoreDataMap();
for (Map.Entry<String, BlockstoreData> entry : blockstoreDataMap.entrySet()) {
Log.d(TAG, String.format(
"Retrieved bytes %s associated with key %s.",
new String(entry.getValue().getBytes()), entry.getKey()));
}
})
.addOnFailureListener(e -> Log.e(TAG, "Failed to store bytes", e));
Kotlin
val client = Blockstore.getClient(this)
val retrieveRequest = RetrieveBytesRequest.Builder()
.setRetrieveAll(true)
.build()
client.retrieveBytes(retrieveRequest)
.addOnSuccessListener { result: RetrieveBytesResponse ->
val blockstoreDataMap =
result.blockstoreDataMap
for ((key, value) in blockstoreDataMap) {
Log.d(ContentValues.TAG, String.format(
"Retrieved bytes %s associated with key %s.",
String(value.bytes), key))
}
}
.addOnFailureListener { e: Exception? ->
Log.e(ContentValues.TAG,
"Failed to store bytes",
e)
}
다음 예시에서는 기본 키를 가져오는 방법을 보여줍니다.
자바
BlockStoreClient client = Blockstore.getClient(this);
RetrieveBytesRequest retrieveRequest = new RetrieveBytesRequest.Builder()
.setKeys(Arrays.asList(BlockstoreClient.DEFAULT_BYTES_DATA_KEY))
.build();
client.retrieveBytes(retrieveRequest);
Kotlin
val client = Blockstore.getClient(this)
val retrieveRequest = RetrieveBytesRequest.Builder()
.setKeys(Arrays.asList(BlockstoreClient.DEFAULT_BYTES_DATA_KEY))
.build()
client.retrieveBytes(retrieveRequest)
토큰 삭제
다음과 같은 이유로 BlockStore에서 토큰을 삭제해야 할 수 있습니다.
- 사용자가 로그아웃 사용자 플로우를 진행합니다.
- 토큰이 취소되었거나 잘못되었습니다.
토큰 검색과 마찬가지로 삭제가 필요한 키 배열을 설정하여 삭제해야 하는 토큰을 지정할 수 있습니다.
다음 예시에서는 특정 키를 삭제하는 방법을 보여줍니다.
자바
BlockstoreClient client = Blockstore.getClient(this);
// Delete data associated with certain keys.
String key1 = "com.example.app.key1";
String key2 = "com.example.app.key2";
String key3 = BlockstoreClient.DEFAULT_BYTES_DATA_KEY; // Used to delete data stored without key
List<String> requestedKeys = Arrays.asList(key1, key2, key3) // Add keys to array
DeleteBytesRequest deleteRequest = new DeleteBytesRequest.Builder()
.setKeys(requestedKeys)
.build();
client.deleteBytes(deleteRequest)
Kotlin
val client = Blockstore.getClient(this)
// Retrieve data associated with certain keys.
val key1 = "com.example.app.key1"
val key2 = "com.example.app.key2"
val key3 = BlockstoreClient.DEFAULT_BYTES_DATA_KEY // Used to retrieve data stored without a key
val requestedKeys = Arrays.asList(key1, key2, key3) // Add keys to array
val retrieveRequest = DeleteBytesRequest.Builder()
.setKeys(requestedKeys)
.build()
client.deleteBytes(retrieveRequest)
모든 토큰 삭제
다음 예에서는 Block Store에 저장된 모든 토큰을 삭제하는 방법을 보여줍니다.
자바
// Delete all data.
DeleteBytesRequest deleteAllRequest = new DeleteBytesRequest.Builder()
.setDeleteAll(true)
.build();
client.deleteBytes(deleteAllRequest)
.addOnSuccessListener(result -> Log.d(TAG, "Any data found and deleted? " + result));
Kotlin
// Delete all data.
val deleteAllRequest = DeleteBytesRequest.Builder()
.setDeleteAll(true)
.build()
client.deleteBytes(deleteAllRequest)
.addOnSuccessListener { result -> Log.d(TAG, "Any data found and deleted? $result") }
엔드 투 엔드 암호화
엔드 투 엔드 암호화를 사용하려면 기기에서 Android 9 이상을 실행해야 하며 사용자가 기기에 화면 잠금(PIN, 패턴 또는 비밀번호)을 설정해야 합니다. isEndToEndEncryptionAvailable()를 호출하여 기기에서 암호화를 사용할 수 있는지 확인할 수 있습니다.
다음 샘플은 클라우드 백업 중에 암호화를 사용할 수 있는지 확인하는 방법을 보여줍니다.
client.isEndToEndEncryptionAvailable()
.addOnSuccessListener { result ->
Log.d(TAG, "Will Block Store cloud backup be end-to-end encrypted? $result")
}
클라우드 백업 사용 설정
클라우드 백업을 사용 설정하려면 setShouldBackupToCloud() 메서드를 StoreBytesData 객체에 추가합니다. Block Store는 setShouldBackupToCloud()가 true로 설정된 경우 저장된 바이트를 클라우드에 주기적으로 백업합니다.
다음 샘플은 클라우드 백업이 엔드 투 엔드 암호화된 경우에만 클라우드 백업을 사용 설정하는 방법을 보여줍니다.
val client = Blockstore.getClient(this)
val storeBytesDataBuilder = StoreBytesData.Builder()
.setBytes(/* BYTE_ARRAY */)
client.isEndToEndEncryptionAvailable()
.addOnSuccessListener { isE2EEAvailable ->
if (isE2EEAvailable) {
storeBytesDataBuilder.setShouldBackupToCloud(true)
Log.d(TAG, "E2EE is available, enable backing up bytes to the cloud.")
client.storeBytes(storeBytesDataBuilder.build())
.addOnSuccessListener { result ->
Log.d(TAG, "stored: ${result.getBytesStored()}")
}.addOnFailureListener { e ->
Log.e(TAG, "Failed to store bytes", e)
}
} else {
Log.d(TAG, "E2EE is not available, only store bytes for D2D restore.")
}
}
테스트 방법
복원 흐름을 테스트하려면 개발 중에 다음 메서드를 사용하세요.
동일한 기기에서 제거 후 재설치
사용자가 백업 서비스를 사용 설정하면(설정 > Google > 백업에서 확인 가능) 앱 제거 및 재설치 전반에서 Block Store 데이터가 유지됩니다.
다음 단계에 따라 테스트할 수 있습니다.
- Block Store API를 테스트 앱에 통합합니다.
- 테스트 앱을 사용하여 Block Store API를 호출하여 데이터를 저장합니다.
- 테스트 앱을 제거한 후 동일한 기기에 앱을 다시 설치합니다.
- 테스트 앱을 사용하여 Block Store API를 호출하여 데이터를 가져옵니다.
- 검색된 바이트가 제거 전에 저장된 바이트와 동일한지 확인합니다.
기기 간
대부분의 경우 대상 기기를 초기화해야 합니다. 그런 다음 Android 무선 복원 흐름 또는 Google 케이블 복원(지원되는 기기의 경우)을 입력할 수 있습니다.
클라우드 복원
- Block Store API를 테스트 앱에 통합합니다. 테스트 앱을 Play 스토어에 제출해야 합니다.
- 소스 기기에서 테스트 앱을 사용하여 Block Store API를 호출하고 데이터를 저장합니다. 이때
shouldBackUpToCloud는true로 설정합니다. - Android 8.0 (API 수준 26) 이상을 실행하는 기기에서는 블록 저장소 클라우드 백업을 수동으로 트리거할 수 있습니다. 설정 > Google > 백업으로 이동하여 '지금 백업' 버튼을 클릭합니다.
- Block Store 클라우드 백업이 성공했는지 확인하려면 다음 단계를 따르세요.
- 백업이 완료되면
[CloudSyncBackupTaskService]태그가 있는 로그 줄을 검색합니다. - 다음과 같은 줄이 표시됩니다.
..., [CloudSyncBackupTaskService] sync result: SUCCESS,..., uploaded size: [size] bytes ...
- 백업이 완료되면
- 블록 스토어 클라우드 백업 후에는 5분의 '대기' 기간이 있습니다. 이 5분 이내에 '지금 백업' 버튼을 클릭해도 다른 Block Store 클라우드 백업이 트리거되지 않습니다.
- Block Store 클라우드 백업이 성공했는지 확인하려면 다음 단계를 따르세요.
- 대상 기기를 초기화하고 클라우드 복원 흐름을 진행합니다. 복원 흐름 중에 테스트 앱을 복원하도록 선택합니다. 클라우드 복원 흐름에 관한 자세한 내용은 지원되는 클라우드 복원 흐름을 참고하세요.
- 대상 기기에서 테스트 앱을 사용하여 블록 저장소 API를 호출하여 데이터를 가져옵니다.
- 검색된 바이트가 소스 기기에 저장된 바이트와 동일한지 확인합니다.
기기 요구사항
블록 저장소 작업에 참여하는 기기의 다음 요구사항을 검토하세요.
엔드 투 엔드 암호화
- 엔드 투 엔드 암호화는 Android 9 (API 29) 이상을 실행하는 기기에서 지원됩니다.
- 엔드 투 엔드 암호화를 사용 설정하고 사용자 데이터를 올바르게 암호화하려면 기기에 PIN, 패턴 또는 비밀번호로 화면 잠금이 설정되어 있어야 합니다.
기기 간 복원 흐름
기기 간 복원을 하려면 소스 기기와 타겟 기기가 있어야 합니다. 데이터를 전송하는 두 기기입니다.
소스 기기는 Android 6 (API 23) 이상을 실행해야 백업할 수 있습니다.
복원 기능을 사용하려면 Android 9 (API 29) 이상을 실행하는 기기를 타겟팅합니다.
기기 간 복원 흐름에 관한 자세한 내용은 지원되는 기기 간 복원 흐름을 참고하세요.
클라우드 백업 및 복원 흐름
클라우드 백업 및 복원에는 소스 기기와 대상 기기가 필요합니다.
소스 기기는 Android 6 (API 23) 이상을 실행해야 백업할 수 있습니다.
대상 기기는 공급업체에 따라 지원됩니다. Pixel 기기는 Android 9 (API 29)부터 이 기능을 사용할 수 있으며 다른 모든 기기는 Android 12 (API 31) 이상을 실행해야 합니다.