사용자가 Google 계정을 사용하여 Firebase에 인증하도록 할 수 있습니다.
시작하기 전에
모듈(앱 수준) Gradle 파일 (일반적으로
<project>/<app-module>/build.gradle
)에서 Firebase 인증 Android 라이브러리에 대한 종속성을 추가합니다. Firebase Android BoM 을 사용하여 라이브러리 버전 관리를 제어하는 것이 좋습니다.또한 Firebase 인증 설정의 일부로 앱에 Google Play 서비스 SDK를 추가해야 합니다.
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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-ktx'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }Firebase Android BoM 을 사용하면 앱에서 항상 호환되는 버전의 Firebase Android 라이브러리를 사용합니다.
(대안) 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-ktx:21.1.0'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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 dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }Firebase Android BoM 을 사용하면 앱에서 항상 호환되는 버전의 Firebase Android 라이브러리를 사용합니다.
(대안) 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:21.1.0'
// Also add the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:20.4.1' }앱의 SHA-1 지문을 아직 지정하지 않은 경우 Firebase 콘솔의 설정 페이지 에서 지정하세요. 앱의 SHA-1 지문을 얻는 방법에 대한 자세한 내용은 클라이언트 인증 을 참조하세요.
- Firebase 콘솔에서 로그인 방법으로 Google을 사용하도록 설정합니다.
- Firebase 콘솔 에서 인증 섹션을 엽니다.
- 로그인 방법 탭에서 Google 로그인 방법을 활성화하고 저장 을 클릭합니다.
Firebase로 인증
- 저장된 사용자 인증 정보로 사용자 로그인 페이지의 단계에 따라 Google One 탭 로그인을 앱에 통합하세요.
BeginSignInRequest
개체를 구성할 때setGoogleIdTokenRequestOptions
를 호출합니다."서버" 클라이언트 ID를Kotlin+KTX
signInRequest = BeginSignInRequest.builder() .setGoogleIdTokenRequestOptions( BeginSignInRequest.GoogleIdTokenRequestOptions.builder() .setSupported(true) // Your server's client ID, not your Android client ID. .setServerClientId(getString(R.string.your_web_client_id)) // Only show accounts previously used to sign in. .setFilterByAuthorizedAccounts(true) .build()) .build()
Java
signInRequest = BeginSignInRequest.builder() .setGoogleIdTokenRequestOptions(GoogleIdTokenRequestOptions.builder() .setSupported(true) // 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()) .build();
setGoogleIdTokenRequestOptions
메소드에 전달해야 합니다. OAuth 2.0 클라이언트 ID를 찾으려면:- GCP 콘솔에서 사용자 인증 정보 페이지 를 엽니다.
- 웹 애플리케이션 유형 클라이언트 ID는 백엔드 서버의 OAuth 2.0 클라이언트 ID입니다.
Kotlin+KTX
class YourActivity : AppCompatActivity() { // ... private val REQ_ONE_TAP = 2 // Can be any integer unique to the Activity private var showOneTapUI = true // ... override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { REQ_ONE_TAP -> { try { val credential = oneTapClient.getSignInCredentialFromIntent(data) val idToken = credential.googleIdToken when { idToken != null -> { // Got an ID token from Google. Use it to authenticate // with Firebase. Log.d(TAG, "Got ID token.") } else -> { // Shouldn't happen. Log.d(TAG, "No ID token!") } } } catch (e: ApiException) { // ... } } } // ... }
Java
public class YourActivity extends AppCompatActivity { // ... private static final int REQ_ONE_TAP = 2; // Can be any integer unique to the Activity. private boolean showOneTapUI = true; // ... @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQ_ONE_TAP: try { SignInCredential credential = oneTapClient.getSignInCredentialFromIntent(data); String idToken = credential.getGoogleIdToken(); if (idToken != null) { // Got an ID token from Google. Use it to authenticate // with Firebase. Log.d(TAG, "Got ID token."); } } catch (ApiException e) { // ... } break; } } }
- 로그인 활동의
onCreate
메소드에서FirebaseAuth
객체의 공유 인스턴스를 가져옵니다.Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- 활동을 초기화할 때 사용자가 현재 로그인되어 있는지 확인하십시오.
Kotlin+KTX
override fun onStart() { super.onStart() // Check if user is signed in (non-null) and update UI accordingly. val currentUser = auth.currentUser updateUI(currentUser) }
Java
@Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. FirebaseUser currentUser = mAuth.getCurrentUser(); updateUI(currentUser); }
-
onActivityResult()
핸들러(1단계 참조)에서 사용자의 Google ID 토큰을 가져와 Firebase 사용자 인증 정보로 교환하고 Firebase 사용자 인증 정보를 사용하여 Firebase에 인증합니다.Kotlin+KTX
val googleCredential = oneTapClient.getSignInCredentialFromIntent(data) val idToken = googleCredential.googleIdToken when { idToken != null -> { // Got an ID token from Google. Use it to authenticate // with Firebase. val firebaseCredential = GoogleAuthProvider.getCredential(idToken, null) auth.signInWithCredential(firebaseCredential) .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) } } } else -> { // Shouldn't happen. Log.d(TAG, "No ID token!") } }
Java
SignInCredential googleCredential = oneTapClient.getSignInCredentialFromIntent(data); String idToken = googleCredential.getGoogleIdToken(); if (idToken != null) { // Got an ID token from Google. Use it to authenticate // with Firebase. AuthCredential firebaseCredential = GoogleAuthProvider.getCredential(idToken, null); mAuth.signInWithCredential(firebaseCredential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> 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 실시간 데이터베이스 및 Cloud Storage 보안 규칙 에서
auth
변수에서 로그인한 사용자의 고유한 사용자 ID를 가져와 사용자가 액세스할 수 있는 데이터를 제어하는 데 사용할 수 있습니다.
인증 공급자 자격 증명을 기존 사용자 계정에 연결하여 사용자가 여러 인증 공급자를 사용하여 앱에 로그인하도록 허용할 수 있습니다.
사용자를 로그아웃하려면 signOut
을 호출합니다.
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();