您可以讓您的用戶使用他們的 Twitter 帳戶通過 Firebase 進行身份驗證,方法是使用 Firebase SDK 將基於 Web 的通用 OAuth 登錄集成到您的應用中,以執行端到端的登錄流程。
在你開始之前
要使用 Twitter 帳戶登錄用戶,您必須首先啟用 Twitter 作為 Firebase 項目的登錄提供程序:
如果您還沒有,請將 Firebase 添加到您的 Android 項目中。
- 在Firebase 控制台中,打開Auth部分。
- 在登錄方法選項卡上,啟用Twitter提供程序。
- 將該提供者的開發者控制台中的API 密鑰和API密鑰添加到提供者配置中:
- 在 Twitter 上將您的應用程序註冊為開發者應用程序並獲取您的應用程序的 OAuth API 密鑰和API 密鑰。
- 確保您的 Firebase OAuth 重定向 URI (例如
my-app-12345.firebaseapp.com/__/auth/handler
)在Twitter 應用的 config的應用設置頁面中設置為您的授權回調 URL 。
- 單擊保存。
使用Firebase Android BoM ,在模塊(應用級)Gradle 文件(通常是
app/build.gradle
)中聲明 Firebase Authentication Android 庫的依賴項。Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.0.1') // 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:21.0.4' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.0.1') // 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 來管理庫版本,以確保所有版本都兼容。
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:21.0.4' }
如果您尚未指定應用的 SHA-1 指紋,請從 Firebase 控制台的“設置”頁面執行此操作。有關如何獲取應用程序的 SHA-1 指紋的詳細信息,請參閱驗證您的客戶端。
使用 Firebase SDK 處理登錄流程
如果您正在構建 Android 應用,使用 Firebase 使用 Twitter 帳戶對用戶進行身份驗證的最簡單方法是使用 Firebase Android SDK 處理整個登錄流程。
要使用 Firebase Android SDK 處理登錄流程,請執行以下步驟:
使用提供者 ID Twitter.com的Builder構造OAuthProvider的實例
OAuthProvider.Builder provider = OAuthProvider.newBuilder("twitter.com");
可選:指定要隨 OAuth 請求一起發送的其他自定義 OAuth 參數。
// Target specific email with login hint. provider.addCustomParameter("lang", "fr");
有關 Twitter 支持的參數,請參閱Twitter OAuth 文檔。請注意,您不能使用
setCustomParameters()
傳遞 Firebase 所需的參數。這些參數是client_id 、 response_type 、 redirect_uri 、 state 、 scope和response_mode 。使用 OAuth 提供程序對象向 Firebase 進行身份驗證。請注意,與其他 FirebaseAuth 操作不同,這將通過彈出Custom Chrome Tab來控制您的 UI。因此,不要在您附加的
OnSuccessListener
和OnFailureListener
中引用您的 Activity,因為它們會在操作啟動 UI 時立即分離。您應該首先檢查您是否已經收到回复。通過此方法登錄會將您的 Activity 置於後台,這意味著它可以在登錄流程中被系統回收。為了確保在發生這種情況時不會讓用戶重試,您應該檢查結果是否已經存在。
要檢查是否有待處理的結果,請調用
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(). // The OAuth secret can be retrieved by calling: // 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
: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(). // The OAuth secret can be retrieved by calling: // authResult.getCredential().getSecret(). } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Handle failure. } });
成功完成後,可以從返回的
OAuthCredential
對像中檢索與提供者關聯的 OAuth 訪問令牌。使用 OAuth 訪問令牌,您可以調用Twitter API 。
例如,要獲取基本配置文件信息,您可以調用 REST API,在
Authorization
標頭中傳遞訪問令牌:雖然上述示例側重於登錄流程,但您還可以使用
startActivityForLinkWithProvider
將 Twitter 提供程序鏈接到現有用戶。例如,您可以將多個提供商鏈接到同一個用戶,允許他們使用其中任何一個登錄。// 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) { // Twitter 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
可以使用相同的模式,它可用於檢索需要最近登錄的敏感操作的新憑據。// 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
:
Java
FirebaseAuth.getInstance().signOut();
Kotlin+KTX
Firebase.auth.signOut()