在 Apple 平台上使用 OpenID Connect 進行驗證

如果您已透過 Identity Platform 升級至 Firebase 驗證,就能使用 使用符合 OpenID Connect (OIDC) 規定的供應商做為 Firebase。這個 能讓您使用 Firebase 未原生支援的識別資訊提供者。

事前準備

如要透過 OIDC 提供者登入使用者,您必須先收集一些資訊 提供者:

  • Client-ID:供應商專用的字串,用於識別您的應用程式。您的 供應商可能會為您支援的每個平台指派不同的用戶端 ID。 這是 aud 憑證附加資訊的其中一個值 (由您的 。

  • 用戶端密鑰:供應商用來確認擁有權的密鑰字串 字串。每個用戶端 ID 都需要相符的用戶端密鑰。 (只有在使用授權碼流程時,才需要這個值, )

  • 核發者:可識別供應器的字串。這個值必須是網址 附加 /.well-known/openid-configuration 後 。舉例來說,如果發卡機構 https://auth.example.com,探索文件必須在以下位置提供: https://auth.example.com/.well-known/openid-configuration

備妥上述資訊後,請在登入時啟用 OpenID Connect 為 Firebase 專案提供供應商:

  1. 將 Firebase 新增至您的 iOS 專案

  2. 如果您尚未升級至 Identity Platform 的 Firebase 驗證,請進行升級。OpenID Connect 驗證 僅適用於已升級的專案。

  3. 登入供應商頁面 在 Firebase 控制台的頁面中,依序點選「新增供應商」OpenID Connect

  4. 選取要使用授權碼流程還是 隱含授權流程

    如果供應商支援程式碼流程,建議您一律使用程式碼流程。 隱含流程的安全性較低,強烈建議不要使用。

  5. 為這個供應商命名。記下產生的提供者 ID: 例如 oidc.example-provider。新增 登入程式碼

  6. 指定您的用戶端 ID 和用戶端密鑰,以及供應商的核發者字串。 這些值必須與供應商指派給您的值完全相符。

  7. 儲存變更。

使用 Firebase SDK 處理登入流程

使用 OIDC 透過 Firebase 驗證使用者最簡單的方式 供應商可透過 Firebase SDK 處理整個登入流程。

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

  1. 在 Xcode 專案中新增自訂網址配置:

    1. 開啟專案設定:按兩下 左側樹狀檢視中從「目標」部分中選取應用程式,然後 選取「資訊」分頁標籤,然後展開「網址類型」部分。
    2. 點選「+」按鈕,然後將經過編碼的應用程式 ID 新增為網址 配置。如要找到經過編碼的應用程式 ID,請前往 一般 Firebase 控制台的「Settings」(設定) 頁面,在 iOS 區段中 應用程式。將其他欄位留白。

      設定完成後,設定看起來應該會與 後面 (但採用您應用程式的專屬值):

      Xcode 自訂網址配置設定介面的螢幕擷取畫面
  2. 使用您取得的提供者 ID 建立 OAuthProvider 的執行個體 也可前往 Firebase 控制台

    Swift

    var provider = OAuthProvider(providerID: "oidc.example-provider")
    

    Objective-C

    FIROAuthProvider *provider = [FIROAuthProvider providerWithProviderID:@"oidc.example-provider"];
    
  3. 選用:指定您想要的其他自訂 OAuth 參數。 與 OAuth 要求一起傳送

    Swift

    provider.customParameters = [
      "login_hint": "user@example.com"
    ]
    

    Objective-C

    [provider setCustomParameters:@{@"login_hint": @"user@example.com"}];
    

    請洽詢您的供應商,瞭解其支援的參數。 請注意,您無法透過 setCustomParameters。這些參數分別是 client_id response_typeredirect_uristatescoperesponse_mode

  4. 選用:指定基本設定檔以外的其他 OAuth 2.0 範圍, 設為要向驗證服務供應商發出要求

    Swift

    provider.scopes = ["mail.read", "calendars.read"]
    

    Objective-C

    [provider setScopes:@[@"mail.read", @"calendars.read"]];
    

    如要瞭解供應商支援的範圍,請洽詢供應商。

  5. 選用:如要自訂應用程式的呈現方式 SFSafariViewControllerUIWebView 符合以下條件時 向使用者顯示 reCAPTCHA 或是建立 設為 AuthUIDelegate 通訊協定

  6. 使用 OAuth 提供者物件向 Firebase 進行驗證。

    Swift

    // If you created a custom class that conforms to AuthUIDelegate,
    // pass it instead of nil:
    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.
          // OAuth access token can also be retrieved:
          // (authResult.credential as? OAuthCredential)?.accessToken
          // OAuth ID token can also be retrieved:
          // (authResult.credential as? OAuthCredential)?.idToken
        }
      }
    }
    

    Objective-C

    // If you created a custom class that conforms to AuthUIDelegate,
    // pass it instead of nil:
    [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.
          // OAuth access token can also be retrieved:
          // ((FIROAuthCredential *)authResult.credential).accessToken
          // OAuth ID token can also be retrieved:
          // ((FIROAuthCredential *)authResult.credential).idToken
        }];
      }
    }];
    
  7. 以上範例著重登入流程,不過您可以 能讓您使用 linkWithCredential。舉例來說 以便將兩者登入

    Swift

    Auth().currentUser.link(withCredential: credential) { authResult, error in
      if error != nil {
        // Handle error.
      }
      // OIDC credential is linked to the current user.
      // IdP data available in authResult.additionalUserInfo.profile.
      // OAuth access token can also be retrieved:
      // (authResult.credential as? OAuthCredential)?.accessToken
      // OAuth ID token can also be retrieved:
      // (authResult.credential as? OAuthCredential)?.idToken
    }
    

    Objective-C

    [[FIRAuth auth].currentUser
        linkWithCredential:credential
                completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
      if (error) {
        // Handle error.
      }
      // OIDC credential is linked to the current user.
      // IdP data available in authResult.additionalUserInfo.profile.
      // OAuth access token can also be retrieved:
      // ((FIROAuthCredential *)authResult.credential).accessToken
      // OAuth ID token can also be retrieved:
      // ((FIROAuthCredential *)authResult.credential).idToken
    }];
    
  8. 相同的模式 reauthenticateWithCredential,可用於 為需要近期執行的敏感作業擷取新憑證 登入。

    Swift

    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 can also be retrieved:
      // (authResult.credential as? OAuthCredential)?.accessToken
      // OAuth ID token can also be retrieved:
      // (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 can also be retrieved:
      // ((FIROAuthCredential *)authResult.credential).accessToken
      // OAuth ID token can also be retrieved:
      // ((FIROAuthCredential *)authResult.credential).idToken
    }];
    

手動處理登入流程

如果應用程式已實作 OpenID Connect 登入流程, 可以直接使用 ID 權杖向 Firebase 進行驗證:

Swift

let credential = OAuthProvider.credential(
    withProviderID: "oidc.example-provider",  // As registered in Firebase console.
    idToken: idToken,  // ID token from OpenID Connect flow.
    rawNonce: nil
)
Auth.auth().signIn(with: credential) { authResult, error in
    if error {
        // Handle error.
        return
    }
    // User is signed in.
    // IdP data available in authResult?.additionalUserInfo?.profile
}

Objective-C

FIROAuthCredential *credential =
    [FIROAuthProvider credentialWithProviderID:@"oidc.example-provider"  // As registered in Firebase console.
                                       IDToken:idToken  // ID token from OpenID Connect flow.
                                      rawNonce:nil];
[[FIRAuth auth] signInWithCredential:credential
                          completion:^(FIRAuthDataResult * _Nullable authResult,
                                      NSError * _Nullable error) {
    if (error != nil) {
        // Handle error.
        return;
    }
    // User is signed in.
    // IdP data available in authResult.additionalUserInfo.profile
}];

後續步驟

使用者首次登入後,系統會建立新的使用者帳戶 也就是使用者的名稱和密碼 號碼或驗證提供者資訊,也就是使用者登入時使用的網址。這項新功能 帳戶儲存為 Firebase 專案的一部分,可用來識別 即可限制使用者登入專案中的所有應用程式

  • 在您的應用程式中,您可以透過 User 物件。請參閱管理使用者

  • 在您的 Firebase 即時資料庫和 Cloud Storage 中 查看安全性規則即可 透過 auth 變數取得已登入使用者的不重複使用者 ID。 控管使用者可以存取的資料

您可以讓使用者透過多重驗證機制登入您的應用程式 將驗證供應商憑證連結至 現有的使用者帳戶

如要登出使用者,請呼叫 signOut:

Swift

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;
}

我們也建議您新增錯誤處理程式碼,適用於完整的驗證範圍 發生錯誤。請參閱處理錯誤