了解 2023 年 Google I/O 大会上介绍的 Firebase 亮点。了解详情

在 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
  4. 選擇 Firebase 身份驗證庫。
  5. 完成後,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;
}

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