Bạn có thể cho phép người dùng của mình xác thực với Firebase bằng Tài khoản Google của họ.
Trước khi bắt đầu
Nếu bạn chưa có, hãy thêm Firebase vào dự án Android của bạn .
Trong tệp Gradle mô-đun (cấp ứng dụng) của bạn (thường là
<project>/<app-module>/build.gradle.kts
hoặc<project>/<app-module>/build.gradle
), hãy thêm phần phụ thuộc cho Xác thực Firebase Thư viện Android. Chúng tôi khuyên bạn nên sử dụng Firebase Android BoM để kiểm soát việc lập phiên bản thư viện.Ngoài ra, trong quá trình thiết lập Xác thực Firebase, bạn cần thêm SDK dịch vụ của Google Play vào ứng dụng của mình.
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:32.3.1")) // 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.7.0") }Bằng cách sử dụng Firebase Android BoM , ứng dụng của bạn sẽ luôn sử dụng các phiên bản tương thích của thư viện Android Firebase.
(Thay thế) Thêm phụ thuộc thư viện Firebase mà không cần sử dụng BoM
Nếu chọn không sử dụng Firebase BoM, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phụ thuộc của nó.
Lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng của mình, chúng tôi thực sự khuyên bạn nên sử dụng BoM để quản lý các phiên bản thư viện, điều này đảm bảo rằng tất cả các phiên bản đều tương thích.
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:22.1.2")
// Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0") }Java
dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:32.3.1")) // 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.7.0") }Bằng cách sử dụng Firebase Android BoM , ứng dụng của bạn sẽ luôn sử dụng các phiên bản tương thích của thư viện Android Firebase.
(Thay thế) Thêm phụ thuộc thư viện Firebase mà không cần sử dụng BoM
Nếu chọn không sử dụng Firebase BoM, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phụ thuộc của nó.
Lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng của mình, chúng tôi thực sự khuyên bạn nên sử dụng BoM để quản lý các phiên bản thư viện, điều này đảm bảo rằng tất cả các phiên bản đều tương thích.
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:22.1.2")
// Also add the dependency for the Google Play services library and specify its version implementation("com.google.android.gms:play-services-auth:20.7.0") }Nếu bạn chưa chỉ định dấu vân tay SHA cho ứng dụng của mình, hãy làm như vậy từ trang Cài đặt của bảng điều khiển Firebase. Tham khảo Xác thực ứng dụng khách của bạn để biết chi tiết về cách lấy dấu vân tay SHA cho ứng dụng của bạn.
- Bật Google làm phương thức đăng nhập trong bảng điều khiển Firebase:
- Trong bảng điều khiển Firebase , hãy mở phần Auth .
- Trên tab Phương thức đăng nhập , bật phương thức đăng nhập Google và nhấp vào Lưu .
Khi được nhắc trong bảng điều khiển, hãy tải xuống tệp cấu hình Firebase đã cập nhật (
google-services.json
), hiện chứa thông tin ứng dụng khách OAuth cần thiết để đăng nhập Google.Di chuyển tệp cấu hình đã cập nhật này vào dự án Android Studio của bạn, thay thế tệp cấu hình tương ứng hiện đã lỗi thời. (Xem Thêm Firebase vào dự án Android của bạn .)
Xác thực với Firebase
- Tích hợp đăng nhập Google One Tap vào ứng dụng của bạn bằng cách làm theo các bước trên trang Đăng nhập người dùng bằng thông tin đăng nhập đã lưu của họ . Khi bạn định cấu hình đối tượng
BeginSignInRequest
, hãy gọisetGoogleIdTokenRequestOptions
:Bạn phải chuyển mã ứng dụng khách "máy chủ" của mình cho phương thứcKotlin+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
. Để tìm ID ứng dụng khách OAuth 2.0:- Mở trang Thông tin xác thực trong Bảng điều khiển GCP.
- ID máy khách loại ứng dụng Web là ID máy khách OAuth 2.0 của máy chủ phụ trợ của bạn.
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; } } }
- Trong phương thức
onCreate
của hoạt động đăng nhập của bạn, lấy phiên bản được chia sẻ của đối tượngFirebaseAuth
:Kotlin+KTX
private lateinit var auth: FirebaseAuth // ... // Initialize Firebase Auth auth = Firebase.auth
Java
private FirebaseAuth mAuth; // ... // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance();
- Khi khởi tạo Hoạt động của bạn, hãy kiểm tra xem người dùng hiện đã đăng nhập chưa:
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); }
- Trong trình xử lý
onActivityResult()
của bạn (xem bước 1), hãy nhận mã thông báo ID Google của người dùng, đổi mã đó lấy thông tin xác thực Firebase và xác thực với Firebase bằng thông tin xác thực Firebase:Nếu lệnh gọiKotlin+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
thành công, bạn có thể sử dụng phương thứcgetCurrentUser
để lấy dữ liệu tài khoản của người dùng.
Bước tiếp theo
Sau khi người dùng đăng nhập lần đầu tiên, tài khoản người dùng mới được tạo và liên kết với thông tin đăng nhập—nghĩa là tên người dùng và mật khẩu, số điện thoại hoặc thông tin nhà cung cấp xác thực—người dùng đã đăng nhập bằng. Tài khoản mới này được lưu trữ như một phần của dự án Firebase của bạn và có thể được sử dụng để xác định người dùng trên mọi ứng dụng trong dự án của bạn, bất kể người dùng đăng nhập bằng cách nào.
Trong các ứng dụng của mình, bạn có thể lấy thông tin hồ sơ cơ bản của người dùng từ đối tượng
FirebaseUser
. Xem Quản lý người dùng .Trong Cơ sở dữ liệu thời gian thực Firebase và Quy tắc bảo mật bộ lưu trữ đám mây , bạn có thể lấy ID người dùng duy nhất của người dùng đã đăng nhập từ biến
auth
và sử dụng biến đó để kiểm soát dữ liệu mà người dùng có thể truy cập.
Bạn có thể cho phép người dùng đăng nhập vào ứng dụng của mình bằng nhiều nhà cung cấp xác thực bằng cách liên kết thông tin đăng nhập của nhà cung cấp xác thực với tài khoản người dùng hiện có.
Để đăng xuất người dùng, hãy gọi signOut
:
Kotlin+KTX
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();