在 Apple 平台上使用 GitHub 進行身份驗證

您可以使用 Firebase SDK 將通用 OAuth 登入整合到您的應用程式中,以執行端對端登入流程,從而讓您的使用者使用 OAuth 提供者(例如 GitHub)透過 Firebase 進行身份驗證。

在你開始之前

若要使用 GitHub 帳戶登入用戶,您必須先啟用 GitHub 作為 Firebase 專案的登入提供者:

使用 Swift Package Manager 安裝和管理 Firebase 相依性。

  1. 在 Xcode 中,開啟應用程式項目,導覽至File > Add Packages
  2. 出現提示時,新增 Firebase Apple 平台 SDK 儲存庫:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. 選擇 Firebase 身份驗證庫。
  5. -ObjC標誌新增至目標建置設定的「其他連結器標誌」部分。
  6. 完成後,Xcode 將自動開始在背景解析並下載您的依賴項。

現在,執行一些設定步驟:

  1. Firebase 控制台中,開啟「驗證」部分。
  2. 登入方法標籤上,啟用GitHub提供者。
  3. 客戶端 ID客戶端金鑰從該提供者的開發人員控制台新增至提供者設定:
    1. 在 GitHub上將您的應用程式註冊為開發人員應用程序,並獲取您的應用程式的 OAuth 2.0 Client IDClient Secret
    2. 確保您的 Firebase OAuth 重定向 URI (例如my-app-12345.firebaseapp.com/__/auth/handler )在GitHub 應用程式 config 的應用程式設定頁面中設定為您的授權回調 URL
  4. 按一下「儲存」

使用 Firebase SDK 處理登入流程

若要使用 Firebase Apple 平台 SDK 處理登入流程,請依照下列步驟操作:

  1. 將自訂 URL 方案新增至您的 Xcode 專案:

    1. 開啟專案配置:雙擊左側樹視圖中的專案名稱。從“目標”部分選擇您的應用程序,然後選擇“資訊”選項卡,並展開“URL 類型”部分。
    2. 點擊+按鈕,並將您的編碼應用程式 ID 新增為 URL 方案。您可以在 Firebase 控制台的「常規設定」頁面上的 iOS 應用程式部分中找到您的編碼應用程式 ID。將其他欄位留空。

      完成後,您的配置應類似於以下內容(但具有特定於應用程式的值):

      Xcode的自訂URL方案設定介面截圖

  2. 使用提供者 ID github.com建立OAuthProvider的實例。

    迅速

        var provider = OAuthProvider(providerID: "github.com")
        

    Objective-C

        FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"github.com"];
        
  3. 可選:指定要與 OAuth 請求一起傳送的其他自訂 OAuth 參數。

    迅速

        provider.customParameters = [
          "allow_signup": "false"
        ]
        

    Objective-C

        [provider setCustomParameters:@{@"allow_signup": @"false"}];
        

    有關 GitHub 支援的參數,請參閱GitHub OAuth 文件。請注意,您無法使用setCustomParameters傳遞 Firebase 所需的參數。這些參數是client_idredirect_uriresponse_typescopestate

  4. 選用:指定您想要從身分驗證提供者要求的基本設定檔以外的其他 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"]
        

    Objective-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 範圍文件

  5. 可選:如果要自訂應用程式在向使用者顯示 reCAPTCHA 時呈現SFSafariViewControllerUIWebView的方式,請建立一個符合AuthUIDelegate協定的自訂類,並將其傳遞給credentialWithUIDelegate

  6. 使用 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
            }
          }
        }
        

    Objective-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
    
  7. 雖然上述範例重點介紹登入流程,但您也可以將 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
        }
        

    Objective-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
        }];
        
  8. 相同的模式可以與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
        }
        

    Objective-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 專案的一部分存儲,並且可用於識別專案中每個應用程式中的用戶,無論用戶如何登入。

  • 在您的應用程式中,您可以從User物件取得使用者的基本個人資料資訊。請參閱管理用戶

  • 在 Firebase 即時資料庫和雲端儲存安全性規則中,您可以從auth變數取得登入使用者的唯一使用者 ID,並使用它來控制使用者可以存取哪些資料。

您可以透過將身分驗證提供者憑證連結到現有使用者帳戶,允許使用者使用多個驗證提供者登入您的應用程式。

若要登出用戶,請呼叫signOut:

迅速

let firebaseAuth = Auth.auth()
do {
  try firebaseAuth.signOut()
} catch let signOutError as NSError {
  print("Error signing out: %@", signOutError)
}

Objective-C

NSError *signOutError;
BOOL status = [[FIRAuth auth] signOut:&signOutError];
if (!status) {
  NSLog(@"Error signing out: %@", signOutError);
  return;
}

您可能還需要為所有身份驗證錯誤新增錯誤處理代碼。請參閱處理錯誤