많은 사용자가 여전히 새 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에 저장하여 나중에 검색할 수 있습니다.
- 토큰은 로컬에 저장되며 클라우드에 백업할 수도 있으며 가능하면 엔드 투 엔드 암호화됩니다.
- 데이터는 사용자가 새 기기에서 복원 흐름을 시작할 때 전송됩니다.
- 사용자가 복원 흐름 중에 앱을 복원하면 앱은 새 기기의 블록 저장소에서 저장된 토큰을 가져올 수 있습니다.
토큰 저장
사용자가 앱에 로그인하면 개발자는 해당 사용자를 위해 생성한 인증 토큰을 블록 스토어에 저장할 수 있습니다. 항목당 최대 4KB의 고유 키 쌍 값을 사용하여 이 토큰을 저장할 수 있습니다. 토큰을 저장하려면 StoreBytesData.Builder
인스턴스에서 setBytes()
및 setKey()
를 호출하여 사용자의 사용자 인증 정보를 소스 기기에 저장합니다. 블록 저장소로 토큰을 저장하면 토큰이 암호화되어 기기에 로컬로 저장됩니다.
다음 샘플은 인증 토큰을 로컬 기기에 저장하는 방법을 보여줍니다.
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));
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));
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()
를 호출하여 블록 스토어에서 토큰을 요청할 수 있습니다. 그러면 검색된 토큰을 사용하여 새 기기에서 사용자의 로그인을 유지할 수 있습니다.
다음 샘플은 특정 키를 기반으로 여러 토큰을 검색하는 방법을 보여줍니다.
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 ListrequestedKeys = 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));
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));
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);
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 ListrequestedKeys = Arrays.asList(key1, key2, key3) // Add keys to array DeleteBytesRequest deleteRequest = new DeleteBytesRequest.Builder() .setKeys(requestedKeys) .build(); client.deleteBytes(deleteRequest)
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)
모든 토큰 삭제
다음 예는 현재 BlockStore에 저장된 모든 토큰을 삭제하는 방법을 보여줍니다.
// 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));
val deleteAllRequest = DeleteBytesRequest.Builder() .setDeleteAll(true) .build() retrieve bytes, the keyBlockstoreClient.DEFAULT_BYTES_DATA_KEY
can be used in theRetrieveBytesRequest
instance in order to get your saved data
The following example shows how to retrieve the default key.
End-to-end encryption
In order for end-to-end encryption to be made available, the device must be
running Android 9 or higher, and the user must have set a screen lock
(PIN, pattern, or password) for their device. You can verify if encryption will
be available on the device by calling isEndToEndEncryptionAvailable()
.
The following sample shows how to verify if encryption will be available during cloud backup:
client.isEndToEndEncryptionAvailable()
.addOnSuccessListener { result ->
Log.d(TAG, "Will Block Store cloud backup be end-to-end encrypted? $result")
}
클라우드 백업 사용 설정
클라우드 백업을 사용 설정하려면 StoreBytesData
객체에 setShouldBackupToCloud()
메서드를 추가합니다. setShouldBackupToCloud()
가 true로 설정된 경우 Block Store는 저장된 바이트를 주기적으로 클라우드에 백업합니다.
다음 샘플은 클라우드 백업이 엔드 투 엔드 암호화된 경우에만 클라우드 백업을 사용 설정하는 방법을 보여줍니다.
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 API를 통합합니다.
- 테스트 앱을 사용하여 Block Store API를 호출하여 데이터를 저장합니다.
- 테스트 앱을 제거한 다음 동일한 기기에 앱을 다시 설치합니다.
- 테스트 앱을 사용하여 Block Store API를 호출하여 데이터를 검색합니다.
- 검색된 바이트가 제거 전에 저장된 것과 동일한지 확인합니다.
기기 간
대부분의 경우 대상 기기를 초기화해야 합니다. 그런 다음 Android 무선 복원 흐름 또는 Google 케이블 복원(지원되는 기기의 경우)을 시작할 수 있습니다.
클라우드 복원
- 테스트 앱에 Block Store API를 통합합니다. 테스트 앱은 Play 스토어에 제출해야 합니다.
- 소스 기기에서 테스트 앱을 사용하여 Block Store API를 호출하여 데이터를 저장합니다(
shouldBackUpToCloud
가true
로 설정됨). - O 이상 기기의 경우 블록 스토어 클라우드 백업을 수동으로 트리거할 수 있습니다. 설정 > Google > 백업으로 이동하여 '지금 백업' 버튼을 클릭합니다.
- Block Store 클라우드 백업이 완료되었는지 확인하려면 다음 단계를 따르세요.
- 백업이 완료되면 'CloudSyncBpTkSvc' 태그가 있는 로그 줄을 검색합니다.
- 다음과 같은 줄이 표시됩니다. '......, CloudSyncBpTkSvc: sync result: SUCCESS, ..., uploaded size: XXX bytes ...'
- Block Store 클라우드 백업 후 5분의 '휴식' 기간이 있습니다. 5분 이내에 '지금 백업' 버튼을 클릭해도 다른 Block Store 클라우드 백업이 트리거되지 않습니다.
- 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) 이상을 실행해야 합니다.