您可以将 Google 登录机制集成到您的应用中,让您的用户可使用自己的 Google 帐号进行 Firebase 身份验证。
准备工作
将 Firebase 添加到您的 Android 项目(如果尚未添加)。
使用 Firebase Android BoM 在模块(应用级)Gradle 文件(通常为
app/build.gradle
)中声明 Firebase Authentication Android 库的依赖项。此外,在设置 Firebase Authentication 时,您还需要将 Google Play 服务 SDK 添加到您的应用中。
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.8.0') // Declare 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 declare the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:19.0.0' }使用 Firebase Android BoM,可确保您的应用始终使用 Firebase Android 库的兼容版本。
(替代方法) 在不使用 BoM 的情况下声明 Firebase 库依赖项
如果您选择不使用 Firebase BoM,则必须在其依赖项行中指定每个 Firebase 库版本。
请注意,如果您在应用中使用多个 Firebase 库,我们强烈建议您使用 BoM 来管理库版本,从而确保所有版本都兼容。
dependencies { // Declare 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:20.0.3'
// Also declare the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:19.0.0' }Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.8.0') // Declare 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 declare the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:19.0.0' }使用 Firebase Android BoM,可确保您的应用始终使用 Firebase Android 库的兼容版本。
(替代方法) 在不使用 BoM 的情况下声明 Firebase 库依赖项
如果您选择不使用 Firebase BoM,则必须在其依赖项行中指定每个 Firebase 库版本。
请注意,如果您在应用中使用多个 Firebase 库,我们强烈建议您使用 BoM 来管理库版本,从而确保所有版本都兼容。
dependencies { // Declare 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:20.0.3'
// Also declare the dependency for the Google Play services library and specify its version implementation 'com.google.android.gms:play-services-auth:19.0.0' }如果您尚未指定应用的 SHA-1 指纹,请在 Firebase 控制台的设置页面中指定。如需详细了解如何获取您应用的 SHA-1 指纹,请参阅对客户端进行身份验证。
- 在 Firebase 控制台中启用 Google 登录机制:
- 在 Firebase 控制台中,打开 Auth 部分。
- 在登录方法标签中,启用 Google 登录方法,然后点击保存。
进行 Firebase 身份验证
- 按照将 Google 登录机制集成到您的 Android 应用页面上的步骤,将 Google 登录机制集成到应用中。
配置
GoogleSignInOptions
对象时,请调用requestIdToken
:Java
// Configure Google Sign In GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
Kotlin+KTX
// Configure Google Sign In val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build() googleSignInClient = GoogleSignIn.getClient(this, gso)
requestIdToken
方法。如需查找 OAuth 2.0 客户端 ID,请执行以下操作:- 打开 GCP Console 中的“凭据”页面。
- Web 应用类型客户端 ID 就是您的后端服务器的 OAuth 2.0 客户端 ID。
Java
private void signIn() { Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); }
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId()); firebaseAuthWithGoogle(account.getIdToken()); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e); } } }
Kotlin+KTX
private fun signIn() { val signInIntent = googleSignInClient.signInIntent startActivityForResult(signInIntent, RC_SIGN_IN) }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) try { // Google Sign In was successful, authenticate with Firebase val account = task.getResult(ApiException::class.java)!! Log.d(TAG, "firebaseAuthWithGoogle:" + account.id) firebaseAuthWithGoogle(account.idToken!!) } catch (e: ApiException) { // Google Sign In failed, update UI appropriately Log.w(TAG, "Google sign in failed", e) } } }
- 在登录 Activity 的
onCreate
方法中,获取FirebaseAuth
对象的共享实例:Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
- 初始化您的 Activity 时,请检查用户当前是否已登录:
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); }
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) }
- 用户成功登录之后,从
GoogleSignInAccount
对象中获取一个 ID 令牌,用其换取 Firebase 凭据,然后使用此 Firebase 凭据进行 Firebase 身份验证:Java
private void firebaseAuthWithGoogle(String idToken) { AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null); mAuth.signInWithCredential(credential) .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); } } }); }
Kotlin+KTX
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) } } }
signInWithCredential
的调用成功,您便可以使用getCurrentUser
方法获取用户的帐号数据。
后续步骤
在用户首次登录后,系统会创建一个新的用户帐号,并将其与该用户登录时使用的凭据(即用户名和密码、电话号码或者身份验证提供方信息)相关联。此新帐号存储在您的 Firebase 项目中,无论用户采用何种方式登录,您项目中的每个应用都可以使用此帐号来识别用户。
-
在您的应用中,您可以从
FirebaseUser
对象中获取用户的基本个人资料信息。请参阅管理用户。 在您的 Firebase Realtime Database 和 Cloud Storage 安全规则中,您可以从
auth
变量获取已登录用户的唯一用户 ID,然后利用此 ID 来控制用户可以访问哪些数据。
您可以通过将身份验证提供方凭据关联至现有用户帐号,让用户可以使用多个身份验证提供方登录您的应用。
如需将用户退出登录,请调用 signOut
:
Java
FirebaseAuth.getInstance().signOut();
Kotlin+KTX
Firebase.auth.signOut()