在 Web 應用程式中使用 OpenID Connect 進行驗證

如果您已升級至使用 Identity Platform 進行 Firebase 驗證,則可以使用您選擇的 OpenID Connect (OIDC) 相容供應商透過 Firebase 對使用者進行驗證。這使得可以使用 Firebase 本身不支援的身份提供者。

在你開始之前

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

  • 客戶端 ID :提供者唯一的字串,用於識別您的應用程式。您的提供者可能會為您支援的每個平台分配不同的客戶端 ID。這是您的提供者頒發的 ID 令牌中的aud聲明的值之一。

  • 客戶端金鑰:提供者用來確認客戶端 ID 所有權的秘密字串。對於每個客戶端 ID,您都需要一個相符的客戶端金鑰。 (僅當您使用auth code flow時才需要此值,強烈建議這樣做。)

  • Issuer :標識您的提供者的字串。該值必須是一個 URL,當附加/.well-known/openid-configuration時,它是提供者的 OIDC 發現文件的位置。例如,如果頒發者是https://auth.example.com ,則發現文件必須位於https://auth.example.com/.well-known/openid-configuration

獲得上述資訊後,啟用 OpenID Connect 作為您的 Firebase 專案的登入提供者:

  1. 將 Firebase 新增到您的 JavaScript 專案

  2. 如果您尚未升級到具有 Identity Platform 的 Firebase 驗證,請升級。 OpenID Connect 驗證僅在升級的專案中可用。

  3. 在 Firebase 控制台的登入提供者頁面上,按一下新增提供者,然後按一下OpenID Connect

  4. 選擇您將使用授權程式碼流程還是隱式授權流程

    如果您的提供者支持,您應該始終使用代碼流。隱式流的安全性較低,強烈建議不要使用它。

  5. 為該提供者指定一個名稱。請注意產生的提供者 ID:類似於oidc.example-provider 。當您向應用程式新增登入代碼時,您將需要此 ID。

  6. 指定您的客戶端 ID 和客戶端金鑰,以及提供者的頒發者字串。這些值必須與您的提供者指派給您的值完全相符。

  7. 儲存您的變更。

使用 Firebase SDK 處理登入流程

使用 OIDC 提供者對 Firebase 使用者進行身份驗證的最簡單方法是使用 Firebase SDK 處理整個登入流程。

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

  1. 使用您在 Firebase 控制台中取得的提供者 ID 建立OAuthProvider的實例。

    網路模組化API

    import { OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('oidc.example-provider');
    

    Web 命名空間 API

    var provider = new firebase.auth.OAuthProvider('oidc.example-provider');
    
  2. 可選:指定要與 OAuth 請求一起傳送的其他自訂 OAuth 參數。

    網路模組化API

    provider.setCustomParameters({
      // Target specific email with login hint.
      login_hint: 'user@example.com'
    });
    

    Web 命名空間 API

    provider.setCustomParameters({
      // Target specific email with login hint.
      login_hint: 'user@example.com'
    });
    

    請諮詢您的提供者以了解其支援的參數。請注意,您無法使用setCustomParameters傳遞 Firebase 所需的參數。這些參數是client_idresponse_typeredirect_uristatescoperesponse_mode

  3. 選用:指定您想要從身分驗證提供者要求的基本設定檔以外的其他 OAuth 2.0 範圍。

    網路模組化API

    provider.addScope('mail.read');
    provider.addScope('calendars.read');
    

    Web 命名空間 API

    provider.addScope('mail.read');
    provider.addScope('calendars.read');
    

    請諮詢您的提供者以了解其支援的範圍。

  4. 使用 OAuth 提供者物件透過 Firebase 進行身份驗證。

    您可以將使用者重新導向至提供者的登入頁面,也可以在彈出的瀏覽器視窗中開啟登入頁面。

    重定向流程

    透過呼叫signInWithRedirect()重定向到提供者登入頁面:

    網路模組化API

    import { getAuth, signInWithRedirect } from "firebase/auth";
    
    const auth = getAuth();
    signInWithRedirect(auth, provider);
    

    Web 命名空間 API

    firebase.auth().signInWithRedirect(provider);
    

    使用者完成登入並傳回應用程式後,您可以透過呼叫getRedirectResult()來取得登入結果。

    網路模組化API

    import { getAuth, getRedirectResult, OAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    getRedirectResult(auth)
      .then((result) => {
        // User is signed in.
        // IdP data available in result.additionalUserInfo.profile.
    
        // Get the OAuth access token and ID Token
        const credential = OAuthProvider.credentialFromResult(result);
        const accessToken = credential.accessToken;
        const idToken = credential.idToken;
      })
      .catch((error) => {
        // Handle error.
      });
    

    Web 命名空間 API

    firebase.auth().getRedirectResult()
      .then((result) => {
        // IdP data available in result.additionalUserInfo.profile.
        // ...
    
        /** @type {firebase.auth.OAuthCredential} */
        var credential = result.credential;
    
        // OAuth access and id tokens can also be retrieved:
        var accessToken = credential.accessToken;
        var idToken = credential.idToken;
      })
      .catch((error) => {
        // Handle error.
      });
    

    彈出流程

    網路模組化API

    import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    signInWithPopup(auth, provider)
      .then((result) => {
        // User is signed in.
        // IdP data available using getAdditionalUserInfo(result)
    
        // Get the OAuth access token and ID Token
        const credential = OAuthProvider.credentialFromResult(result);
        const accessToken = credential.accessToken;
        const idToken = credential.idToken;
      })
      .catch((error) => {
        // Handle error.
      });
    

    Web 命名空間 API

    firebase.auth().signInWithPopup(provider)
      .then((result) => {
        // IdP data available in result.additionalUserInfo.profile.
        // ...
    
        /** @type {firebase.auth.OAuthCredential} */
        var credential = result.credential;
    
        // OAuth access and id tokens can also be retrieved:
        var accessToken = credential.accessToken;
        var idToken = credential.idToken;
      })
      .catch((error) => {
        // Handle error.
      });
    
  5. 雖然上面的範例重點關注登入流程,但您可以使用相同的模式使用linkWithRedirect()linkWithPopup()將 OIDC 提供者連結到現有用戶,並使用reauthenticateWithRedirect() )和reauthenticateWithPopup()於檢索需要最近登入的敏感操作的新憑證。

手動處理登入流程

如果您已在應用程式中實作 OpenID Connect 登入流程,則可以直接使用 ID 令牌透過 Firebase 進行驗證:

網路模組化API

import { getAuth, signInWithCredential, OAuthProvider } from "firebase/auth";

const provider = new OAuthProvider("oidc.example-provider");
const credential = provider.credential({
    idToken: idToken,
});
signInWithCredential(getAuth(), credential)
    .then((result) => {
        // User is signed in.
        // IdP data available in result.additionalUserInfo.profile.

        // Get the OAuth access token and ID Token
        const credential = OAuthProvider.credentialFromResult(result);
        const accessToken = credential.accessToken;
        const idToken = credential.idToken;
    })
    .catch((error) => {
        // Handle error.
    });

Web 命名空間 API

const provider = new OAuthProvider("oidc.example-provider");
const credential = provider.credential({
    idToken: idToken,
});
firebase.auth().signInWithCredential(credential)
    .then((result) => {
        // User is signed in.
        // IdP data available in result.additionalUserInfo.profile.

        // Get the OAuth access token and ID Token
        const credential = OAuthProvider.credentialFromResult(result);
        const accessToken = credential.accessToken;
        const idToken = credential.idToken;
    })
    .catch((error) => {
        // Handle error.
    });