您可以使用Firebase SDK通過將基於Web的通用OAuth登錄集成到您的應用中,從而使用戶使用其GitHub帳戶通過Firebase進行身份驗證,以執行端到端登錄流程。
在你開始之前
要使用GitHub帳戶登錄用戶,您必須首先啟用GitHub作為Firebase項目的登錄提供程序:
- 在Firebase控制台中,打開“身份驗證”部分。
- 在“登錄方法”選項卡上,啟用GitHub提供程序。
- 從該提供程序的開發人員控制台將客戶端ID和客戶端密鑰添加到提供程序配置中:
- 在GitHub上將您的應用註冊為開發人員應用,並獲取應用的OAuth 2.0客戶端ID和客戶端密鑰。
- 確保您的Firebase OAuth重定向URI (例如,
my-app-12345.firebaseapp.com/__/auth/handler
)已在GitHub應用程序配置的應用程序設置頁面中設置為授權回調URL 。
- 點擊保存。
使用Firebase Android BoM ,在模塊(應用程序級)Gradle文件(通常為
app/build.gradle
)中聲明Firebase Authentication Android庫的依賴app/build.gradle
。爪哇
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.3.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' }
通過使用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.2' }
Kotlin + KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:26.3.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' }
通過使用Firebase Android BoM ,您的應用將始終使用Firebase Android庫的兼容版本。
(可選)不使用BoM聲明Firebase庫依賴關係
如果選擇不使用Firebase BoM,則必須在其依賴關係行中指定每個Firebase庫版本。
請注意,如果您在應用中使用多個Firebase庫,我們強烈建議您使用BoM來管理庫版本,以確保所有版本兼容。
第0946章如果您尚未指定應用的SHA-1指紋,請從Firebase控制台的“設置”頁面中進行指定。有關如何獲取應用程序的SHA-1指紋的詳細信息,請參閱身份驗證客戶端。
使用Firebase SDK處理登錄流程
如果您正在構建Android應用,則使用用戶的GitHub帳戶向Firebase進行身份驗證的最簡單方法是使用Firebase Android SDK處理整個登錄流程。
要使用Firebase Android SDK處理登錄流程,請按照以下步驟操作:
使用帶有提供者ID github.com的Builder構建OAuthProvider的實例
OAuthProvider.Builder provider = OAuthProvider.newBuilder("github.com");
可選:指定要與OAuth請求一起發送的其他自定義OAuth參數。
// 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權限下請求訪問GitHub API的權限。請求的OAuth範圍必須與應用的API權限中的預配置範圍完全匹配。
// 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標籤”來控制您的UI。因此,請勿在您附加的
OnSuccessListener
和OnFailureListener
中引用您的Activity,因為它們將在操作啟動UI時立即分離。您應該首先檢查是否已經收到回复。通過此方法登錄會將您的活動置於後台,這意味著在登錄流程中系統可以收回該活動。為了確保您不會在這種情況下使用戶再試一次,應該檢查結果是否已經存在。
要檢查是否有待處理的結果,請調用
getPendingAuthResult
: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: // authResult.getCredential().getAccessToken(). } }) .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
: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: // authResult.getCredential().getAccessToken(). } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle failure. } });
成功完成後,可以從返回的
OAuthCredential
對OAuthCredential
檢索與提供者關聯的OAuth訪問令牌。使用OAuth訪問令牌,您可以調用GitHub API 。
例如,要獲取基本的配置文件信息,您可以調用REST API,並在
Authorization
標頭中傳遞訪問令牌:儘管以上示例著重於登錄流程,但您也可以使用
startActivityForLinkWithProvider
將GitHub提供程序鏈接到現有用戶。例如,您可以將多個提供程序鏈接到同一用戶,從而允許他們使用任一者登錄。// 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) { // GitHub 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(). } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle failure. } });
可以將同一模式與
startActivityForReauthenticateWithProvider
一起使用,該模式可用於檢索需要最近登錄的敏感操作的新憑據。// 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實時數據庫和雲存儲安全規則中,您可以從
auth
變量中獲取登錄用戶的唯一用戶ID,然後使用它來控制用戶可以訪問哪些數據。
通過將身份驗證提供程序憑據鏈接到現有用戶帳戶,可以允許用戶使用多個身份驗證提供程序登錄您的應用程序。
要註銷用戶,請致電signOut
:
爪哇
FirebaseAuth.getInstance().signOut();
Kotlin + KTX
Firebase.auth.signOut()