사용자가 Google 계정을 사용하여 Firebase에 인증하도록 설정할 수 있습니다.
시작하기 전에
아직 추가하지 않았다면 Android 프로젝트에 Firebase를 추가합니다.
모듈(앱 수준) Gradle 파일(일반적으로
<project>/<app-module>/build.gradle.kts
또는<project>/<app-module>/build.gradle
)에서 Android용 Firebase Authentication 라이브러리의 종속 항목을 추가합니다. 라이브러리 버전 관리 제어에는 Firebase Android BoM을 사용하는 것이 좋습니다.또한 Firebase Authentication을 설정하는 과정에서 앱에 인증 관리자 SDK를 추가해야 합니다.
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.9.0")) // Add the dependency for the Firebase Authentication library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-auth")
// Also add the dependencies for the Credential Manager libraries and specify their versions implementation("androidx.credentials:credentials:1.3.0") implementation("androidx.credentials:credentials-play-services-auth:1.3.0") implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1") }Firebase Android BoM을 사용하면 앱에서 항상 호환되는 Firebase Android 라이브러리 버전만 사용합니다.
Kotlin 전용 라이브러리 모듈을 찾고 계신가요? 2023년 10월(Firebase BoM 32.5.0)부터 Kotlin 및 Java 개발자 모두 기본 라이브러리 모듈을 사용할 수 있습니다. 자세한 내용은 이 이니셔티브에 관한 FAQ를 참조하세요.(대안) BoM을 사용하지 않고 Firebase 라이브러리 종속 항목을 추가합니다.
Firebase BoM을 사용하지 않도록 선택한 경우에는 종속 항목 줄에 각 Firebase 라이브러리 버전을 지정해야 합니다.
앱에서 여러 Firebase 라이브러리를 사용하는 경우 모든 버전이 호환되도록 BoM을 사용하여 라이브러리 버전을 관리하는 것이 좋습니다.
dependencies { // Add the dependency for the Firebase Authentication library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-auth:23.2.0")
// Also add the dependencies for the Credential Manager libraries and specify their versions implementation("androidx.credentials:credentials:1.3.0") implementation("androidx.credentials:credentials-play-services-auth:1.3.0") implementation("com.google.android.libraries.identity.googleid:googleid:1.1.1") }아직 앱의 SHA-1 디지털 지문을 지정하지 않았다면 Firebase Console의 설정 페이지에서 지정합니다. 앱의 SHA 디지털 지문을 얻는 방법에 대한 자세한 내용은 클라이언트 인증을 참조하세요.
- Firebase Console에서 Google을 로그인 방법으로 사용 설정합니다.
- Firebase Console에서 인증 섹션을 엽니다.
- 로그인 방법 탭에서 Google 로그인 방법을 사용 설정하고 저장을 클릭합니다.
Console에 메시지가 표시되면 업데이트된 Firebase 구성 파일(
google-services.json
)을 다운로드합니다. 여기에 Google 로그인에 필요한 OAuth 클라이언트 정보가 포함됩니다.업데이트된 구성 파일을 Android 스튜디오 프로젝트로 이동하여 기존의 오래된 구성 파일을 교체합니다. (Android 프로젝트에 Firebase 추가를 참조하세요.)
Firebase에 인증
- 인증 관리자 문서의 단계에 따라 앱에 Google 계정으로 로그인을 통합합니다. 대략적인 안내는 다음과 같습니다.
GetGoogleIdOption
을 사용하여 Google 로그인 요청을 인스턴스화합니다. 그런 다음GetCredentialRequest
를 사용하여 인증 관리자 요청을 만듭니다.// Instantiate a Google sign-in request val googleIdOption = GetGoogleIdOption.Builder() // Your server's client ID, not your Android client ID. .setServerClientId(getString(R.string.default_web_client_id)) // Only show accounts previously used to sign in. .setFilterByAuthorizedAccounts(true) .build() // Create the Credential Manager request val request = GetCredentialRequest.Builder() .addCredentialOption(googleIdOption) .build()
// Instantiate a Google sign-in request GetGoogleIdOption googleIdOption = new GetGoogleIdOption.Builder() .setFilterByAuthorizedAccounts(true) .setServerClientId(getString(R.string.default_web_client_id)) .build(); // Create the Credential Manager request GetCredentialRequest request = new GetCredentialRequest.Builder() .addCredentialOption(googleIdOption) .build();
위의 요청에서
setServerClientId
메서드에 '서버' 클라이언트 ID를 전달해야 합니다. OAuth 2.0 클라이언트 ID를 확인하는 방법은 다음과 같습니다.- Google Cloud 콘솔에서 사용자 인증 정보 페이지를 엽니다.
- 웹 애플리케이션 유형의 클라이언트 ID가 백엔드 서버의 OAuth 2.0 클라이언트 ID입니다.
- Google 계정으로 로그인을 통합한 후 로그인 활동의 코드가 다음과 유사한지 확인합니다.
private fun handleSignIn(credential: Credential) { // Check if credential is of type Google ID if (credential is CustomCredential && credential.type == TYPE_GOOGLE_ID_TOKEN_CREDENTIAL) { // Create Google ID Token val googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credential.data) // Sign in to Firebase with using the token firebaseAuthWithGoogle(googleIdTokenCredential.idToken) } else { Log.w(TAG, "Credential is not of type Google ID!") } }
private void handleSignIn(Credential credential) { // Check if credential is of type Google ID if (credential instanceof CustomCredential customCredential && credential.getType().equals(TYPE_GOOGLE_ID_TOKEN_CREDENTIAL)) { // Create Google ID Token Bundle credentialData = customCredential.getData(); GoogleIdTokenCredential googleIdTokenCredential = GoogleIdTokenCredential.createFrom(credentialData); // Sign in to Firebase with using the token firebaseAuthWithGoogle(googleIdTokenCredential.getIdToken()); } else { Log.w(TAG, "Credential is not of type Google ID!"); } }
- 다음과 같이 로그인 작업의
onCreate
메서드에서FirebaseAuth
객체의 공유 인스턴스를 가져옵니다.private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- 활동을 초기화할 때 사용자가 현재 로그인되어 있는지 확인합니다.
override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) }
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); updateUI(currentUser); }
- 이제 1단계에서 만든 사용자의 Google ID 토큰을 가져와서 Firebase 사용자 인증 정보로 교환하고 Firebase 사용자 인증 정보를 사용하여 Firebase에 인증합니다.
private fun firebaseAuthWithGoogle(idToken: String) { val credential = GoogleAuthProvider.getCredential(idToken, null) auth.signInWithCredential(credential) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success") val user = auth.currentUser updateUI(user) } else { // If sign in fails, display a message to the user Log.w(TAG, "signInWithCredential:failure", task.exception) updateUI(null) } } }
private void firebaseAuthWithGoogle(String idToken) { AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, task -> { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithCredential:success"); FirebaseUser user = mAuth.getCurrentUser(); updateUI(user); } else { // If sign in fails, display a message to the user Log.w(TAG, "signInWithCredential:failure", task.getException()); updateUI(null); } }); }
signInWithCredential
에 대한 호출이 성공하면getCurrentUser
메서드로 사용자의 계정 데이터를 가져올 수 있습니다.
다음 단계
사용자가 처음으로 로그인하면 신규 사용자 계정이 생성되고 사용자가 로그인할 때 사용한 사용자 인증 정보(사용자 이름과 비밀번호, 전화번호 또는 인증 제공업체 정보)에 연결됩니다. 이 신규 계정은 Firebase 프로젝트에 저장되며 사용자의 로그인 방법과 무관하게 프로젝트 내의 모든 앱에서 사용자 본인 확인에 사용할 수 있습니다.
앱의
FirebaseUser
객체에서 사용자의 기본 프로필 정보를 가져올 수 있습니다. 사용자 관리를 참조하세요.Firebase Realtime Database와 Cloud Storage 보안 규칙의
auth
변수에서 로그인한 사용자의 고유 사용자 ID를 가져온 후 이 ID를 통해 사용자가 액세스할 수 있는 데이터를 관리할 수 있습니다.
인증 제공업체의 사용자 인증 정보를 기존 사용자 계정에 연결하면 사용자가 여러 인증 제공업체를 통해 앱에 로그인할 수 있습니다.
사용자를 로그아웃시키려면 signOut
을 호출합니다. 또한 인증 관리자 문서에 권장된 대로 모든 사용자 인증 정보 제공업체에서 현재 사용자 인증 정보 상태를 삭제해야 합니다.
private fun signOut() { // Firebase sign out auth.signOut() // When a user signs out, clear the current user credential state from all credential providers. lifecycleScope.launch { try { val clearRequest = ClearCredentialStateRequest() credentialManager.clearCredentialState(clearRequest) updateUI(null) } catch (e: ClearCredentialException) { Log.e(TAG, "Couldn't clear user credentials: ${e.localizedMessage}") } } }
private void signOut() { // Firebase sign out mAuth.signOut(); // When a user signs out, clear the current user credential state from all credential providers. ClearCredentialStateRequest clearRequest = new ClearCredentialStateRequest(); credentialManager.clearCredentialStateAsync( clearRequest, new CancellationSignal(), Executors.newSingleThreadExecutor(), new CredentialManagerCallback<>() { @Override public void onResult(@NonNull Void result) { updateUI(null); } @Override public void onError(@NonNull ClearCredentialException e) { Log.e(TAG, "Couldn't clear user credentials: " + e.getLocalizedMessage()); } }); }