您可以讓您的用戶使用 GitHub 等 OAuth 提供商通過 Firebase 進行身份驗證,方法是使用 Firebase SDK 將通用 OAuth 登錄集成到您的應用程序中以執行端到端登錄流程。
在你開始之前
要使用 GitHub 帳戶登錄用戶,您必須首先啟用 GitHub 作為您的 Firebase 項目的登錄提供商:
使用 Swift Package Manager 安裝和管理 Firebase 依賴項。
- 在 Xcode 中,打開您的應用程序項目,導航至File > Add Packages 。
- 出現提示時,添加 Firebase Apple 平台 SDK 存儲庫:
- 選擇 Firebase 身份驗證庫。
- 完成後,Xcode 將自動開始在後台解析和下載您的依賴項。
https://github.com/firebase/firebase-ios-sdk
現在,執行一些配置步驟:
- 在Firebase 控制台中,打開Auth部分。
- 在登錄方法選項卡上,啟用GitHub提供程序。
- 將該提供商的開發人員控制台中的客戶端 ID和客戶端密碼添加到提供商配置中:
- 在 GitHub上將您的應用程序註冊為開發人員應用程序,並獲取您應用程序的 OAuth 2.0 Client ID和Client Secret 。
- 確保您的 Firebase OAuth 重定向 URI (例如
my-app-12345.firebaseapp.com/__/auth/handler
)在您的GitHub 應用的配置頁面中設置為您的授權回調 URL 。
- 單擊保存。
使用 Firebase SDK 處理登錄流程
要使用 Firebase Apple 平台 SDK 處理登錄流程,請執行以下步驟:
將自定義 URL 方案添加到您的 Xcode 項目:
- 打開您的項目配置:雙擊左側樹視圖中的項目名稱。從TARGETS部分選擇您的應用程序,然後選擇Info選項卡,並展開URL Types部分。
- 單擊+按鈕,並將您的編碼應用程序 ID 添加為 URL 方案。您可以在 Firebase 控制台的常規設置頁面上的 iOS 應用程序部分找到您的編碼應用程序 ID。將其他字段留空。
完成後,您的配置應類似於以下內容(但具有特定於應用程序的值):
使用提供者 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"]
目標-C
// 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
的方式,請創建一個符合AuthUIDelegate
協議的自定義類,並將其傳遞給credentialWithUIDelegate
。使用 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 as? OAuthCredential)?.accessToken // GitHub OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.idToken }
目標-C
[[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: // ((FIROAuthCredential *)authResult.credential).accessToken // GitHub OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)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 as? OAuthCredential)?.accessToken // GitHub OAuth ID token can be retrieved by calling: // (authResult.credential as? OAuthCredential)?.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: // ((FIROAuthCredential *)authResult.credential).accessToken // GitHub OAuth ID token can be retrieved by calling: // ((FIROAuthCredential *)authResult.credential).idToken }];
下一步
用戶首次登錄後,將創建一個新的用戶帳戶並將其鏈接到用戶登錄所用的憑據,即用戶名和密碼、電話號碼或身份驗證提供商信息。這個新帳戶存儲為您的 Firebase 項目的一部分,可用於在項目中的每個應用程序中識別用戶,無論用戶如何登錄。
在您的 Firebase Realtime Database 和 Cloud Storage Security Rules中,您可以從
auth
變量中獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問的數據。
您可以允許用戶使用多個身份驗證提供程序登錄您的應用程序,方法是將身份驗證提供程序憑據鏈接到現有用戶帳戶。
要註銷用戶,請調用signOut:
。
迅速
let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() } catch let signOutError as NSError { print("Error signing out: %@", signOutError) }
目標-C
NSError *signOutError; BOOL status = [[FIRAuth auth] signOut:&signOutError]; if (!status) { NSLog(@"Error signing out: %@", signOutError); return; }
您可能還想為所有身份驗證錯誤添加錯誤處理代碼。請參閱處理錯誤。