透過 JavaScript 使用 Yahoo 驗證

您可以使用 Firebase SDK 將通用 OAuth 登入功能整合至應用程式,執行端對端登入流程,讓使用者透過 Yahoo 等 OAuth 提供者驗證 Firebase。

事前準備

如要讓使用者使用 Yahoo 帳戶登入,您必須先將 Yahoo 設為 Firebase 專案的登入提供者:

  1. 將 Firebase 新增至 JavaScript 專案
  2. Firebase 控制台中,開啟「Auth」部分。
  3. 在「Sign in method」分頁中,啟用 Yahoo 供應器。
  4. 將該供應商開發人員控制台的「Client ID」和「Client Secret」新增至供應商設定:
    1. 如要註冊 Yahoo OAuth 用戶端,請按照 Yahoo 開發人員說明文件中的說明 向 Yahoo 註冊網路應用程式

      請務必選取兩個 OpenID Connect API 權限:profileemail

    2. 向這些供應商註冊應用程式時,請務必將專案的 *.firebaseapp.com 網域註冊為應用程式的重新導向網域。
  5. 按一下 [儲存]

使用 Firebase SDK 處理登入流程

如果您要建構網頁應用程式,透過 Firebase 驗證使用者是否使用 Yahoo 帳戶,最簡單的方法就是使用 Firebase JavaScript SDK 處理整個登入流程。

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

  1. 使用提供者 ID yahoo.com 建立 OAuthProvider 例項。

    WebWeb
    import { OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('yahoo.com');
    var provider = new firebase.auth.OAuthProvider('yahoo.com');
  2. 選用:指定您要透過 OAuth 要求傳送的其他自訂 OAuth 參數。

    WebWeb
    provider.setCustomParameters({
      // Prompt user to re-authenticate to Yahoo.
      prompt: 'login',
      // Localize to French.
      language: 'fr'
    });  
    provider.setCustomParameters({
      // Prompt user to re-authenticate to Yahoo.
      prompt: 'login',
      // Localize to French.
      language: 'fr'
    });  

    如要瞭解 Yahoo 支援的參數,請參閱 Yahoo OAuth 說明文件。請注意,您無法使用 setCustomParameters() 傳遞 Firebase 必要參數。這些參數包括 client_idredirect_uriresponse_typescopestate

  3. 選用:指定您要向驗證服務供應商要求的其他 OAuth 2.0 範圍,除了 profileemail 以外。如果您的應用程式需要存取 Yahoo API 中的私人使用者資料,您必須在 Yahoo 開發人員控制台的「API 權限」下,要求 Yahoo API 的權限。要求的 OAuth 範圍必須與應用程式 API 權限中預先設定的範圍完全相符。舉例來說,如果您要求存取使用者聯絡人的讀/寫權限,並在應用程式的 API 權限中預先設定,就必須傳遞 sdct-w,而非唯讀 OAuth 範圍 sdct-r。否則流程將失敗,並向使用者顯示錯誤訊息。

    WebWeb
    // Request access to Yahoo Mail API.
    provider.addScope('mail-r');
    // Request read/write access to user contacts.
    // This must be preconfigured in the app's API permissions.
    provider.addScope('sdct-w');
    // Request access to Yahoo Mail API.
    provider.addScope('mail-r');
    // Request read/write access to user contacts.
    // This must be preconfigured in the app's API permissions.
    provider.addScope('sdct-w');

    詳情請參閱 Yahoo 範圍說明文件

  4. 使用 OAuth 提供者物件與 Firebase 進行驗證。您可以開啟彈出式視窗或重新導向至登入頁面,提示使用者使用 Yahoo 帳戶登入。在行動裝置上,建議使用重新導向方法。

    • 如要透過彈出式視窗登入,請呼叫 signInWithPopup

      WebWeb
      import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
      
      const auth = getAuth();
      signInWithPopup(auth, provider)
        .then((result) => {
          // IdP data available in result.additionalUserInfo.profile
          // ...
      
          // Yahoo OAuth access token and ID token can be retrieved by calling:
          const credential = OAuthProvider.credentialFromResult(result);
          const accessToken = credential.accessToken;
          const idToken = credential.idToken;
        })
        .catch((error) => {
          // Handle error.
        });
      firebase.auth().signInWithPopup(provider)
        .then((result) => {
          // IdP data available in result.additionalUserInfo.profile
          // ...
      
          /** @type {firebase.auth.OAuthCredential} */
          const credential = result.credential;
      
          // Yahoo OAuth access token and ID token can be retrieved by calling:
          var accessToken = credential.accessToken;
          var idToken = credential.idToken;
        })
        .catch((error) => {
          // Handle error.
        });
    • 如要透過重新導向登入頁面來登入,請呼叫 signInWithRedirect

    使用 signInWithRedirectlinkWithRedirectreauthenticateWithRedirect 時,請遵循最佳做法

      firebase.auth().signInWithRedirect(provider);
      

    使用者完成登入並返回頁面後,您可以呼叫 getRedirectResult 取得登入結果。

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

    完成後,您可以從傳回的 firebase.auth.UserCredential 物件中擷取與提供者相關聯的 OAuth ID 權杖和存取權杖。

    您可以使用 OAuth 存取權杖呼叫 Yahoo API

    舉例來說,如要取得基本設定檔資訊,您可以呼叫下列 REST API:

    curl -i -H "Authorization: Bearer ACCESS_TOKEN" https://social.yahooapis.com/v1/user/YAHOO_USER_UID/profile?format=json

    其中 YAHOO_USER_UID 是 Yahoo 使用者 ID,可從 firebase.auth().currentUser.providerData[0].uid 欄位或 result.additionalUserInfo.profile 擷取。

  5. 雖然上述範例著重於登入流程,但您也可以使用 linkWithPopup/linkWithRedirect 將 Yahoo 提供者連結至現有使用者。舉例來說,您可以將多個提供者連結至同一位使用者,讓他們使用任一提供者登入。

    WebWeb
    import { getAuth, linkWithPopup, OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('yahoo.com');
    const auth = getAuth();
    linkWithPopup(auth.currentUser, provider)
        .then((result) => {
          // Yahoo credential is linked to the current user.
          // 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.
        });
    var provider = new firebase.auth.OAuthProvider('yahoo.com');
    firebase.auth().currentUser.linkWithPopup(provider)
        .then((result) => {
          // Yahoo credential is linked to the current user.
          // IdP data available in result.additionalUserInfo.profile.
          // Yahoo OAuth access token can be retrieved by calling:
          // result.credential.accessToken
          // Yahoo OAuth ID token can be retrieved by calling:
          // result.credential.idToken
        })
        .catch((error) => {
          // Handle error.
        });
  6. reauthenticateWithPopup/reauthenticateWithRedirect 可使用相同的模式,可用於擷取敏感作業的最新憑證,這些作業需要最近的登入作業。

    WebWeb
    import { getAuth, reauthenticateWithPopup, OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('yahoo.com');
    const auth = getAuth();
    reauthenticateWithPopup(auth.currentUser, provider)
        .then((result) => {
          // 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.
    
          // 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.
        });
    var provider = new firebase.auth.OAuthProvider('yahoo.com');
    firebase.auth().currentUser.reauthenticateWithPopup(provider)
        .then((result) => {
          // 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.
          // Yahoo OAuth access token can be retrieved by calling:
          // result.credential.accessToken
          // Yahoo OAuth ID token can be retrieved by calling:
          // result.credential.idToken
        })
        .catch((error) => {
          // Handle error.
        });

如果您在 Firebase 控制台中啟用「每個電子郵件地址只能建立一個帳戶」設定,當使用者嘗試使用另一個 Firebase 使用者供應商 (例如 Google) 的電子郵件地址登入供應商 (例如 Yahoo) 時,系統會擲回錯誤 auth/account-exists-with-different-credential,並附上 AuthCredential 物件 (Yahoo 憑證)。如要完成登入指定提供者的程序,使用者必須先登入現有提供者 (Google),然後連結至前述的 AuthCredential (Yahoo 憑證)。

如果您使用 signInWithPopup,可以使用以下程式碼處理 auth/account-exists-with-different-credential 錯誤:

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

try {
  // Step 1: User tries to sign in using Yahoo.
  let result = await signInWithPopup(getAuth(), new OAuthProvider());
} catch (error) {
  // Step 2: User's email already exists.
  if (error.code === "auth/account-exists-with-different-credential") {
    // The pending Yahoo credential.
    let pendingCred = error.credential;

    // Step 3: Save the pending credential in temporary storage,

    // Step 4: Let the user know that they already have an account
    // but with a different provider, and let them choose another
    // sign-in method.
  }
}

// ...

try {
  // Step 5: Sign the user in using their chosen method.
  let result = await signInWithPopup(getAuth(), userSelectedProvider);

  // Step 6: Link to the Yahoo credential.
  // TODO: implement `retrievePendingCred` for your app.
  let pendingCred = retrievePendingCred();

  if (pendingCred !== null) {
    // As you have access to the pending credential, you can directly call the
    // link method.
    let user = await linkWithCredential(result.user, pendingCred);
  }

  // Step 7: Continue to app.
} catch (error) {
  // ...
}

重新導向模式

在重新導向模式中,系統會以類似方式處理這項錯誤,但差別在於,系統必須在網頁重新導向期間快取待處理的憑證 (例如使用工作階段儲存空間)。

與 Firebase 支援的其他 OAuth 供應商 (例如 Google、Facebook 和 Twitter) 不同,Firebase 驗證無法為 Yahoo 等供應商提供相同的功能,因為 Firebase 驗證伺服器無法驗證 Yahoo OAuth 存取權權杖的目標對象。這是一項重要的安全性規定,如果應用程式和網站遭到重播攻擊,攻擊者可利用為某個專案 (攻擊者) 取得的 Yahoo OAuth 存取權權杖,登入另一個專案 (受害者)。相反地,Firebase Auth 可使用 Firebase 主控台中設定的 OAuth 用戶端 ID 和秘密,處理整個 OAuth 流程和授權碼交換作業。由於授權碼只能與特定用戶端 ID/密鑰搭配使用,因此無法將為一個專案取得的授權碼用於其他專案。

如果您需要在未支援的環境中使用這些提供者,就必須使用第三方 OAuth 程式庫和 Firebase 自訂驗證。前者用於與供應商進行驗證,後者則用於交換供應商的憑證,以取得自訂權杖。

在 Chrome 擴充功能中使用 Firebase 進行驗證

如果您要建構 Chrome 擴充功能應用程式,請參閱 離線文件指南

建立專案時,Firebase 會為您的專案提供專屬子網域:https://my-app-12345.firebaseapp.com

這也會用來做為 OAuth 登入的重新導向機制。您必須為所有支援的 OAuth 供應商允許該網域。不過,這也表示使用者在登入 Yahoo 時,可能會看到以下網域,然後才會重新導向至應用程式:Continue to: https://my-app-12345.firebaseapp.com

如要避免顯示子網域,您可以使用 Firebase Hosting 設定自訂網域:

  1. 請按照「Hosting 設定網域」中的步驟 1 至 3 操作。驗證網域擁有權後,Hosting 會為自訂網域佈建 SSL 憑證。
  2. 將自訂網域新增至 Firebase 控制台的授權網域清單:auth.custom.domain.com
  3. 在 Yahoo 開發人員控制台或 OAuth 設定頁面中,將重新導向網頁的網址加入白名單,這樣您就能透過自訂網域 https://auth.custom.domain.com/__/auth/handler 存取該網頁。
  4. 初始化 JavaScript 程式庫時,請使用 authDomain 欄位指定自訂網域:
    var config = {
      apiKey: '...',
      // Changed from 'PROJECT_ID.firebaseapp.com'.
      authDomain: 'auth.custom.domain.com',
      databaseURL: 'https://PROJECT_ID.firebaseio.com',
      projectId: 'PROJECT_ID',
      storageBucket: 'PROJECT_ID.firebasestorage.app',
      messagingSenderId: 'SENDER_ID'
    };
    firebase.initializeApp(config);

後續步驟

使用者首次登入後,系統會建立新使用者帳戶,並連結至使用者登入時所用的憑證 (即使用者名稱和密碼、電話號碼或驗證服務提供者資訊)。這個新帳戶會儲存在 Firebase 專案中,無論使用者如何登入,都可以用於在專案中的每個應用程式中識別使用者。

  • 在應用程式中,建議您在 Auth 物件上設定觀察器,以便瞭解使用者的驗證狀態。接著,您可以從 User 物件取得使用者的基本個人資料資訊。請參閱「管理使用者」。

  • Firebase Realtime DatabaseCloud Storage 安全性規則中,您可以從 auth 變數取得已登入使用者的專屬使用者 ID,並利用該 ID 控管使用者可存取的資料。

您可以將驗證服務供應商憑證連結至現有使用者帳戶,讓使用者使用多個驗證服務供應商登入應用程式。

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

WebWeb
import { getAuth, signOut } from "firebase/auth";

const auth = getAuth();
signOut(auth).then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});
firebase.auth().signOut().then(() => {
  // Sign-out successful.
}).catch((error) => {
  // An error happened.
});