通過使用Firebase SDK將通用OAuth登錄集成到您的應用中,可以執行端到端登錄流程,從而使用戶可以使用GitHub等OAuth提供程序通過Firebase進行身份驗證。
在你開始之前
要使用GitHub帳戶登錄用戶,必須首先啟用GitHub作為Firebase項目的登錄提供程序:
- 將Firebase添加到您的iOS項目。
pod 'Firebase/Auth'
- 在Firebase控制台中,打開“身份驗證”部分。
- 在“登錄方法”選項卡上,啟用GitHub提供程序。
- 從該提供程序的開發人員控制台將客戶端ID和客戶端密鑰添加到提供程序配置中:
- 在GitHub上將您的應用註冊為開發人員應用,並獲取應用的OAuth 2.0客戶端ID和客戶端密鑰。
- 確保您的Firebase OAuth重定向URI (例如,
my-app-12345.firebaseapp.com/__/auth/handler
)在GitHub應用程序配置的應用程序設置頁面中設置為授權回調URL 。
- 點擊保存。
使用Firebase SDK處理登錄流程
要使用Firebase iOS SDK處理登錄流程,請按照以下步驟操作:
將自定義URL方案添加到您的Xcode項目中:
- 打開項目配置:在左樹視圖中雙擊項目名稱。從“目標”部分中選擇您的應用,然後選擇“信息”選項卡,然後展開“ URL類型”部分。
- 單擊+按鈕,然後為您的反向客戶端ID添加URL方案。要找到此值,請打開
配置文件,然後查找GoogleService-Info.plist REVERSED_CLIENT_ID
密鑰。複製該鍵的值,然後將其粘貼到配置頁上的“ URL方案”框中。將其他字段留空。完成後,您的配置應類似於以下內容(但具有特定於應用程序的值):
使用提供程序ID github.com創建OAuthProvider的實例。
迅速
var provider = OAuthProvider(providerID: "github.com")
目標C
FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"github.com"];
可選:指定要與OAuth請求一起發送的其他自定義OAuth參數。
迅速
provider.customParameters = [ "allow_signup": "false" ]
目標C
[provider setCustomParameters:@{@"allow_signup": @"false"}];
有關GitHub支持的參數,請參閱GitHub OAuth文檔。請注意,您無法使用
setCustomParameters
傳遞Firebase必需的參數。這些參數是client_id , redirect_uri , response_type , scope和state 。可選:指定要從身份驗證提供程序請求的基本配置文件之外的其他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. provider.scopes = ["user:email"]
物鏡
// Request read access to a user's email addresses. // This must be preconfigured in the app's API permissions. [provider setScopes:@[@"user:email"]];
要了解更多信息,請參閱GitHub作用域文檔。
可選:如果要自定義應用程序在向用戶顯示reCAPTCHA時呈現
SFSafariViewController
或UIWebView
的方式,請創建一個符合FIRAuthUIDelegate
協議的自定義類,並將其傳遞給getCredentialWithUIDelegate:completion:
FIRAuthUIDelegate
使用OAuth提供程序對象向Firebase進行身份驗證。
迅速
provider.getCredentialWith(nil) { credential, error in if error != nil { // Handle error. } if credential != nil { Auth().signIn(with: credential) { authResult, error in if error != nil { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. guard let oauthCredential = authResult.credential as? OAuthCredential else { return } // GitHub OAuth access token can also be retrieved by: // oauthCredential.accessToken // GitHub OAuth ID token can be retrieved by calling: // oauthCredential.idToken } } }
目標C
[provider getCredentialWithUIDelegate:nil completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) { if (error) { // Handle error. } if (credential) { [[FIRAuth auth] signInWithCredential:credential completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) { if (error) { // Handle error. } // User is signed in. // IdP data available in authResult.additionalUserInfo.profile. FIROAuthCredential *oauthCredential = (FIROAuthCredential *)authResult.credential; // GitHub OAuth access token can also be retrieved by: // oauthCredential.accessToken // GitHub OAuth ID token can be retrieved by calling: // oauthCredential.idToken }]; } }];
使用OAuth訪問令牌,您可以調用GitHub API 。
例如,要獲取基本的配置文件信息,可以調用REST API,並在
Authorization
標頭中傳遞訪問令牌:https://api.github.com/user
儘管以上示例著重於登錄流程,但您還可以將GitHub提供程序鏈接到現有用戶。例如,您可以將多個提供程序鏈接到同一用戶,從而允許他們使用任一者登錄。
迅速
Auth().currentUser.link(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // GitHub credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // GitHub OAuth access token can also be retrieved by: // authResult.credential.accessToken // GitHub OAuth ID token can be retrieved by calling: // authResult.credential.idToken }
物鏡
[[FIRAuth auth].currentUser linkWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // GitHub credential is linked to the current user. // IdP data available in authResult.additionalUserInfo.profile. // GitHub OAuth access token is can also be retrieved by: // authResult.credential.accessToken // GitHub OAuth ID token can be retrieved by calling: // authResult.credential.idToken }];
可以將同一模式與
reauthenticateWithCredential
一起使用,該模式可用於檢索需要最近登錄的敏感操作的新憑據。迅速
Auth().currentUser.reauthenticateWithCredential(withCredential: credential) { authResult, error in if error != nil { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token is can also be retrieved by: // authResult.credential.accessToken // GitHub OAuth ID token can be retrieved by calling: // authResult.credential.idToken }
目標C
[[FIRAuth auth].currentUser reauthenticateWithCredential:credential completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) { if (error) { // Handle error. } // User is re-authenticated with fresh tokens minted and // should be able to perform sensitive operations like account // deletion and email or password update. // IdP data available in result.additionalUserInfo.profile. // Additional OAuth access token is can also be retrieved by: // authResult.credential.accessToken // GitHub OAuth ID token can be retrieved by calling: // authResult.credential.idToken }];
下一步
用戶首次登錄後,將創建一個新的用戶帳戶並將其鏈接到該用戶登錄的憑據(即用戶名和密碼,電話號碼或身份驗證提供者信息)。此新帳戶存儲為Firebase項目的一部分,可用於在項目中的每個應用程序中識別用戶,而無論用戶如何登錄。
在Firebase實時數據庫和雲存儲安全規則中,您可以從
auth
變量中獲取登錄用戶的唯一用戶ID,並使用它來控制用戶可以訪問哪些數據。
通過將身份驗證提供程序憑據鏈接到現有用戶帳戶,可以允許用戶使用多個身份驗證提供程序登錄您的應用程序。
要註銷用戶,請致電signOut:
迅速
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print ("Error signing out: %@", signOutError) }
物鏡
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
您可能還想為所有身份驗證錯誤添加錯誤處理代碼。請參閱處理錯誤。