透過 JavaScript 使用 Yahoo 驗證

您可以使用 Firebase SDK 將一般 OAuth 登入整合至您的應用程式,讓使用者透過 OAuth 供應商向 Firebase 進行驗證,藉此執行端對端登入流程。

事前準備

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

  1. 將 Firebase 新增至您的 JavaScript 專案
  2. Firebase 控制台開啟「驗證」專區。
  3. 在「登入方式」分頁中,啟用 Yahoo 供應商。
  4. 從供應商的 Play 管理中心,新增「用戶端 ID」和「用戶端密鑰」到供應商設定:
    1. 如要註冊 Yahoo OAuth 用戶端,請按照 Yahoo 開發人員說明文件 向 Yahoo 註冊網頁應用程式中的指示操作。

      請務必選取以下兩項 OpenID Connect API 權限:profileemail

    2. 向這些供應商註冊應用程式時,請務必為專案的 *.firebaseapp.com 網域註冊應用程式的重新導向網域。
  5. 點選「Save」

使用 Firebase SDK 處理登入流程

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

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

  1. 使用提供者 ID yahoo.com 建立 OAuthProvider 的執行個體。

    網頁模組 API

    import { OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('yahoo.com');

    網路命名空間 API

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

    網頁模組 API

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

    網路命名空間 API

    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。否則資料流會失敗,且使用者會看到錯誤訊息。

    網頁模組 API

    // 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');

    網路命名空間 API

    // 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

      網頁模組 API

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

      網路命名空間 API

      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 來取得登入結果。

    網頁模組 API

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

    網路命名空間 API

    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 是可從 firebase.auth().currentUser.providerData[0].uid 欄位或 result.additionalUserInfo.profile 擷取的 Yahoo 使用者 ID。

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

    網頁模組 API

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

    網路命名空間 API

    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 搭配使用,針對需要近期登入的敏感作業擷取最新憑證。

    網頁模組 API

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

    網路命名空間 API

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

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

如要建構 Chrome 擴充功能應用程式,請參閱 螢幕外文件指南

後續步驟

使用者首次登入時,系統會建立新的使用者帳戶,並連結至憑證 (即使用者名稱與密碼、電話號碼或驗證提供者資訊),也就是使用者登入時使用的憑證。這個新帳戶會儲存在您的 Firebase 專案中,可用來識別專案中各個應用程式的使用者 (無論使用者登入方式為何)。

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

  • 在 Firebase 即時資料庫和 Cloud Storage 安全性規則中,您可以透過 auth 變數取得登入使用者的專屬 ID,並使用該 ID 控管使用者可存取哪些資料。

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

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

網頁模組 API

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

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

網路命名空間 API

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