您可以將網頁式一般 OAuth 登入機制整合至應用程式,讓使用者透過 GitHub 帳戶進行 Firebase 驗證。請使用 Firebase SDK 執行端對端登入流程。
事前準備
如要讓使用者透過 GitHub 帳戶登入,您必須先在 Firebase 專案中啟用 GitHub 做為登入供應商:
如果您尚未將 Firebase 新增至 Android 專案,請先新增。
- 在 Firebase 控制台中,依序前往 「Security」(安全性) >「Authentication」(驗證)。
- 在「登入方式」分頁中,啟用「GitHub」登入供應商。
-
將該供應商開發人員控制台中的「Client ID」(用戶端 ID) 和「Client Secret」(用戶端密鑰) 新增至供應商設定:
- 在 GitHub 上將應用程式註冊為開發人員應用程式,並取得應用程式的 OAuth 2.0 用戶端 ID 和用戶端密鑰。
-
在 GitHub 應用程式設定的應用程式設定頁面中,確認 Firebase OAuth 重新導向 URI (例如
my-app-12345.firebaseapp.com/__/auth/handler) 已設為授權回呼網址。
- 按一下「儲存」。
在模組 (應用程式層級) Gradle 檔案 (通常是
<project>/<app-module>/build.gradle.kts或<project>/<app-module>/build.gradle) 中,新增 Android Firebase Authentication 程式庫的依附元件。建議使用 Firebase Android BoM 控制程式庫版本管理。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:35.1.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") }
只要使用 Firebase Android BoM,應用程式就會一律使用相容的 Firebase Android 程式庫版本。
(替代方案) 新增 Firebase 程式庫依附元件,不使用 BoM
如果選擇不使用 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:25.0.0") }
指定應用程式的 SHA-1 指紋 (如果尚未指定)。
在 Firebase 控制台中,依序前往「
Settings 」(設定) >「General」(一般) 分頁。向下捲動至「您的應用程式」資訊卡,選取 Android 應用程式,然後在「SHA 憑證指紋」欄位中新增 SHA-1 指紋。
如要瞭解如何取得應用程式的 SHA 指紋,請參閱「驗證用戶端」。
使用 Firebase SDK 處理登入流程
如果您正在建構 Android 應用程式,最簡單的方法是使用 Firebase Android SDK 處理整個登入流程,讓使用者透過 GitHub 帳戶進行 Firebase 驗證。
如要使用 Firebase Android SDK 處理登入流程,請按照下列步驟操作:
使用 OAuthProvider 的 Builder 建構執行個體,並將供應商 ID 設為 github.com
Kotlin
val provider = OAuthProvider.newBuilder("github.com")
Java
OAuthProvider.Builder provider = OAuthProvider.newBuilder("github.com");
選用:指定要與 OAuth 要求一併傳送的其他自訂 OAuth 參數。
Kotlin
// Target specific email with login hint. provider.addCustomParameter("login", "your-email@gmail.com")
Java
// Target specific email with login hint. provider.addCustomParameter("login", "your-email@gmail.com");
如要瞭解 GitHub 支援的參數,請參閱 GitHub OAuth 說明文件。請注意,您無法使用
setCustomParameters()傳遞 Firebase 必要的參數。這些參數包括 client_id、response_type、redirect_uri、state、scope 和 response_mode。選用:指定要向驗證服務供應商要求的其他 OAuth 2.0 範圍 (基本設定檔除外)。如果應用程式需要透過 GitHub API 存取私人使用者資料,您必須在 GitHub 開發人員控制台的「API Permissions」(API 權限) 下方,要求存取 GitHub API 的權限。要求的 OAuth 範圍必須與應用程式 API 權限中預先設定的範圍完全相符。
Kotlin
// Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. provider.scopes = listOf("user:email")
Java
// Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. List<String> scopes = new ArrayList<String>() { { add("user:email"); } }; provider.setScopes(scopes);
使用 OAuth 供應商物件向 Firebase 驗證。請注意,與其他 FirebaseAuth 作業不同,這項作業會彈出自訂 Chrome 分頁,接管使用者介面。因此,請勿在附加的
OnSuccessListener和OnFailureListener中參照 Activity,因為作業啟動 UI 時,這些項目會立即卸載。請先確認是否已收到回覆。透過這個方法登入會將 Activity 移至背景,這表示系統可能會在登入流程中回收 Activity。為確保使用者在這種情況下不必重試,請檢查是否已有結果。
如要檢查是否有待處理的結果,請呼叫
getPendingAuthResult:Kotlin
val pendingResultTask = firebaseAuth.pendingAuthResult if (pendingResultTask != null) { // There's something already here! Finish the sign-in for your user. pendingResultTask .addOnSuccessListener { // User is signed in. // IdP data available in // authResult.getAdditionalUserInfo().getProfile(). // The OAuth access token can also be retrieved: // ((OAuthCredential)authResult.getCredential()).getAccessToken(). // The OAuth secret can be retrieved by calling: // ((OAuthCredential)authResult.getCredential()).getSecret(). } .addOnFailureListener { // Handle failure. } } else { // There's no pending result so you need to start the sign-in flow. // See below. }
Java
Task<AuthResult> pendingResultTask = firebaseAuth.getPendingAuthResult(); if (pendingResultTask != null) { // There's something already here! Finish the sign-in for your user. pendingResultTask .addOnSuccessListener( new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { // User is signed in. // IdP data available in // authResult.getAdditionalUserInfo().getProfile(). // The OAuth access token can also be retrieved: // ((OAuthCredential)authResult.getCredential()).getAccessToken(). // The OAuth secret can be retrieved by calling: // ((OAuthCredential)authResult.getCredential()).getSecret(). } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle failure. } }); } else { // There's no pending result so you need to start the sign-in flow. // See below. }
如要啟動登入流程,請呼叫
startActivityForSignInWithProvider:Kotlin
firebaseAuth .startActivityForSignInWithProvider(activity, provider.build()) .addOnSuccessListener { // User is signed in. // IdP data available in // authResult.getAdditionalUserInfo().getProfile(). // The OAuth access token can also be retrieved: // ((OAuthCredential)authResult.getCredential()).getAccessToken(). // The OAuth secret can be retrieved by calling: // ((OAuthCredential)authResult.getCredential()).getSecret(). } .addOnFailureListener { // Handle failure. }
Java
firebaseAuth .startActivityForSignInWithProvider(/* activity= */ this, provider.build()) .addOnSuccessListener( new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { // User is signed in. // IdP data available in // authResult.getAdditionalUserInfo().getProfile(). // The OAuth access token can also be retrieved: // ((OAuthCredential)authResult.getCredential()).getAccessToken(). // The OAuth secret can be retrieved by calling: // ((OAuthCredential)authResult.getCredential()).getSecret(). } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle failure. } });
成功完成後,您可以從傳回的
OAuthCredential物件中,擷取與供應商相關聯的 OAuth 存取權杖。您可以使用 OAuth 存取權杖呼叫 GitHub API。
舉例來說,如要取得基本個人資料資訊,您可以呼叫 REST API,並在
Authorization標頭中傳遞存取權杖:雖然上述範例著重於登入流程,但您也可以使用
startActivityForLinkWithProvider將 GitHub 供應商連結至現有使用者。舉例來說,您可以將多個供應商連結至同一位使用者,讓他們能使用任一供應商登入。Kotlin
// The user is already signed-in. val firebaseUser = firebaseAuth.currentUser!! firebaseUser .startActivityForLinkWithProvider(activity, provider.build()) .addOnSuccessListener { // Provider credential is linked to the current user. // IdP data available in // authResult.getAdditionalUserInfo().getProfile(). // The OAuth access token can also be retrieved: // authResult.getCredential().getAccessToken(). // The OAuth secret can be retrieved by calling: // authResult.getCredential().getSecret(). } .addOnFailureListener { // Handle failure. }
Java
// The user is already signed-in. FirebaseUser firebaseUser = firebaseAuth.getCurrentUser(); firebaseUser .startActivityForLinkWithProvider(/* activity= */ this, provider.build()) .addOnSuccessListener( new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { // Provider credential is linked to the current user. // IdP data available in // authResult.getAdditionalUserInfo().getProfile(). // The OAuth access token can also be retrieved: // authResult.getCredential().getAccessToken(). // The OAuth secret can be retrieved by calling: // authResult.getCredential().getSecret(). } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle failure. } });
startActivityForReauthenticateWithProvider也可以使用相同的模式,用於擷取需要近期登入的機密作業的新憑證。Kotlin
// The user is already signed-in. val firebaseUser = firebaseAuth.currentUser!! firebaseUser .startActivityForReauthenticateWithProvider(activity, provider.build()) .addOnSuccessListener { // User is re-authenticated with fresh tokens and // should be able to perform sensitive operations // like account deletion and email or password // update. } .addOnFailureListener { // Handle failure. }
Java
// The user is already signed-in. FirebaseUser firebaseUser = firebaseAuth.getCurrentUser(); firebaseUser .startActivityForReauthenticateWithProvider(/* activity= */ this, provider.build()) .addOnSuccessListener( new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { // User is re-authenticated with fresh tokens and // should be able to perform sensitive operations // like account deletion and email or password // update. } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle failure. } });
後續步驟
使用者首次登入後,系統會建立新的使用者帳戶,並連結至使用者登入時使用的憑證,也就是使用者名稱和密碼、電話號碼或驗證供應商資訊。這個新帳戶會儲存為 Firebase 專案的一部分,無論使用者如何登入,都可用來識別專案中所有應用程式的使用者。
-
在應用程式中,您可以從
FirebaseUser物件取得使用者的基本個人資料。請參閱「 管理使用者」。 在 Firebase Realtime Database 和 Cloud Storage 安全性規則中,您可以從
auth變數取得已登入使用者的專屬使用者 ID,並用來控管使用者可存取的資料。
您可以將驗證供應商憑證連結至現有使用者帳戶,允許使用者透過多個驗證供應商登入應用程式。
如要登出使用者,請呼叫
signOut:
Kotlin
Firebase.auth.signOut()
Java
FirebaseAuth.getInstance().signOut();