您可以讓使用者使用 OAuth 供應商在 Firebase 進行驗證,例如: 透過 Firebase SDK 將一般 OAuth 登入整合至您的應用程式,以實現 GitHub 的 執行端對端登入流程
事前準備
如要使用 GitHub 帳戶登入使用者,必須先啟用 GitHub 登入功能 為 Firebase 專案提供供應商:
使用 Swift Package Manager 安裝及管理 Firebase 依附元件。
- 在 Xcode 中保持開啟應用程式專案,然後前往「檔案」檔案 >新增套件。
- 在系統提示時,新增 Firebase Apple 平台 SDK 存放區:
- 選擇 Firebase Authentication 程式庫。
- 在目標建構設定的「Other Linker Flags」部分中新增
-ObjC
標記。 - 完成後,Xcode 會自動開始解析並下載 複製到背景依附元件
https://github.com/firebase/firebase-ios-sdk.git
現在,請執行一些設定步驟:
- 在 Firebase 控制台中開啟「Auth」專區。
- 在「Sign in method」分頁中,啟用 GitHub 供應商。
- 將供應商開發人員主控台中的「用戶端 ID」和「用戶端密鑰」新增至
提供者設定:
- 註冊應用程式 下載為 GitHub 上的開發人員應用程式,並取得應用程式的 OAuth 2.0 用戶端 ID 和用戶端密鑰。
- 請確認您的 Firebase OAuth 重新導向 URI (例如
my-app-12345.firebaseapp.com/__/auth/handler
) 在應用程式「設定」頁面的「授權回呼網址」中, GitHub 應用程式的設定。
- 按一下 [儲存]。
使用 Firebase SDK 處理登入流程
如要使用 Firebase Apple 平台 SDK 處理登入流程,請按照下列步驟操作:
在 Xcode 專案中新增自訂網址配置:
- 開啟專案設定:按兩下 左側樹狀檢視中從「目標」部分中選取應用程式,然後 選取「資訊」分頁標籤,然後展開「網址類型」部分。
- 點選「+」按鈕,然後將經過編碼的應用程式 ID 新增為網址
配置。如要找到經過編碼的應用程式 ID,請前往
一般
Firebase 控制台的「設定」頁面,位於 iOS 裝置的專區
應用程式。將其他欄位留白。
設定完成後,設定看起來應該會與 後面 (但採用您應用程式的專屬值):
使用提供者 ID 建立 OAuthProvider 執行個體 github.com:
var provider = OAuthProvider(providerID: "github.com")
FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"github.com"];
選用:指定您想要的其他自訂 OAuth 參數。 與 OAuth 要求一起傳送
provider.customParameters = [ "allow_signup": "false" ]
[provider setCustomParameters:@{@"allow_signup": @"false"}];
如需 GitHub 支援的參數,請參閱 GitHub OAuth 說明文件。 請注意,您無法透過
setCustomParameters
。這些參數都是 client_id redirect_uri、response_type、scope 和 state。選用:指定基本設定檔以外的其他 OAuth 2.0 範圍, 設為要向驗證服務供應商發出要求如果您的應用程式 需要透過 GitHub API 存取使用者的私人資料,您必須 要求存取 GitHub API 的 API 權限 GitHub 開發人員主控台。要求的 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 範圍說明文件。
選用:如要自訂應用程式的呈現方式
SFSafariViewController
或UIWebView
符合以下條件時 向使用者顯示 reCAPTCHA 或是建立 並傳遞至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 } } }
[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 }
[[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 }
[[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 控制台中啟用「每個電子郵件地址一個帳戶」設定:
使用者嘗試使用現有的電子郵件地址登入供應商 (例如 GitHub) 時
也存在於其他 Firebase 使用者的供應商 (例如 Google) 中,因此發生錯誤
FIRAuthErrorCodeAccountExistsWithDifferentCredential
會與臨時暫存檔一起擲回
FIRAuthCredential
物件 (GitHub 憑證)。如要完成
使用者必須先登入現有的供應商 (Google),才能連結至
先前的 FIRAuthCredential
(GitHub 憑證)。如下所示:
// Sign-in with an OAuth credential. provider.getCredentialWith(nil) { credential, error in // An account with the same email already exists. if (error as NSError?)?.code == AuthErrorCode.accountExistsWithDifferentCredential.rawValue { // Get pending credential and email of existing account. let existingAcctEmail = (error! as NSError).userInfo[AuthErrorUserInfoEmailKey] as! String let pendingCred = (error! as NSError).userInfo[AuthErrorUserInfoUpdatedCredentialKey] as! AuthCredential // Lookup existing account identifier by the email. Auth.auth().fetchProviders(forEmail:existingAcctEmail) { providers, error in // Existing email/password account. if (providers?.contains(EmailAuthProviderID))! { // Existing password account for email. Ask user to provide the password of the // existing account. // Sign in with existing account. Auth.auth().signIn(withEmail:existingAcctEmail, password:password) { user, error in // Successfully signed in. if user != nil { // Link pending credential to account. Auth.auth().currentUser?.linkAndRetrieveData(with: pendingCred) { result, error in // ... } } } } } return } // Other errors. if error != nil { // handle the error. return } // Sign in with the credential. if credential != nil { Auth.auth().signInAndRetrieveData(with: credential!) { result, error in if error != nil { // handle the error. return } } } }
// Sign-in with an OAuth credential. [provider getCredentialWithUIDelegate:nil completion:^(FIRAuthCredential *_Nullable credential, NSError *_Nullable error) { // An account with the same email already exists. if (error.code == FIRAuthErrorCodeAccountExistsWithDifferentCredential) { // Get pending credential and email of existing account. NSString *existingAcctEmail = error.userInfo[FIRAuthErrorUserInfoEmailKey]; FIRAuthCredential *pendingCred = error.userInfo[FIRAuthErrorUserInfoUpdatedCredentialKey]; // Lookup existing account identifier by the email. [[FIRAuth auth] fetchProvidersForEmail:existingAcctEmail completion:^(NSArray<NSString *> *_Nullable providers, NSError *_Nullable error) { // Existing email/password account. if ( [providers containsObject:FIREmailAuthProviderID] ) { // Existing password account for email. Ask user to provide the password of the // existing account. // Sign in with existing account. [[FIRAuth auth] signInWithEmail:existingAcctEmail password:password completion:^(FIRUser *user, NSError *error) { // Successfully signed in. if (user) { // Link pending credential to account. [[FIRAuth auth].currentUser linkWithCredential:pendingCred completion:^(FIRUser *_Nullable user, NSError *_Nullable error) { // ... }]; } }]; } }]; return; } // Other errors. if (error) { // handle the error. return; } // Sign in with the credential. if (credential) { [[FIRAuth auth] signInAndRetrieveDataWithCredential:credential completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) { if (error) { // handle the error. return; } }]; } }];
後續步驟
使用者首次登入後,系統會建立新的使用者帳戶 也就是使用者的名稱和密碼 號碼或驗證提供者資訊,也就是使用者登入時使用的網址。這項新功能 帳戶儲存為 Firebase 專案的一部分,可用來識別 即可限制使用者登入專案中的所有應用程式
在你的Firebase Realtime Database和Cloud Storage中 查看安全性規則 透過
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; }
我們也建議您新增錯誤處理程式碼,適用於完整的驗證範圍 發生錯誤。請參閱處理錯誤。