使用 Microsoft 與 JavaScript 進行驗證,使用 Microsoft 與 JavaScript 進行驗證

您可以使用 Firebase SDK 將通用 OAuth 登入整合到您的應用程式中,以執行端對端登入流程,讓您的使用者可以使用 Microsoft Azure Active Directory 等 OAuth 提供者透過 Firebase 進行驗證。

在你開始之前

若要使用 Microsoft 帳戶(Azure Active Directory 和個人 Microsoft 帳戶)登入用戶,您必須先啟用 Microsoft 作為 Firebase 專案的登入提供者:

  1. 將 Firebase 新增到您的 JavaScript 專案
  2. Firebase 控制台中,開啟「驗證」部分。
  3. 「登入方法」標籤上,啟用Microsoft提供者。
  4. 客戶端 ID客戶端金鑰從該提供者的開發人員控制台新增至提供者設定:
    1. 若要註冊 Microsoft OAuth 用戶端,請依照快速入門:向 Azure Active Directory v2.0 終端點註冊應用程式中的說明進行操作。請注意,此終結點支援使用 Microsoft 個人帳戶以及 Azure Active Directory 帳號登入。了解更多有關 Azure Active Directory v2.0 的資訊
    2. 向這些提供者註冊應用程式時,請務必將專案的*.firebaseapp.com網域註冊為應用程式的重新導向網域。
  5. 按一下「儲存」

使用 Firebase SDK 處理登入流程

如果您正在建立 Web 應用程序,使用 Microsoft 帳戶透過 Firebase 對使用者進行身份驗證的最簡單方法是使用 Firebase JavaScript SDK 處理整個登入流程。

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

  1. 使用提供者 ID microsoft.com建立OAuthProvider的實例。

    Web modular API

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

    Web namespaced API

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

    Web modular API

    provider.setCustomParameters({
      // Force re-consent.
      prompt: 'consent',
      // Target specific email with login hint.
      login_hint: 'user@firstadd.onmicrosoft.com'
    });

    Web namespaced API

    provider.setCustomParameters({
      // Force re-consent.
      prompt: 'consent',
      // Target specific email with login hint.
      login_hint: 'user@firstadd.onmicrosoft.com'
    });

    有關 Microsoft 支援的參數,請參閱Microsoft OAuth 文件。請注意,您無法使用setCustomParameters()傳遞 Firebase 所需的參數。這些參數是client_idresponse_typeredirect_uristatescoperesponse_mode

    若要僅允許特定 Azure AD 租用戶的使用者登入應用程序,可以使用 Azure AD 租用戶的友善網域名稱或租用戶的 GUID 識別碼。這可以透過在自訂參數物件中指定“租戶”欄位來完成。

    Web modular API

    provider.setCustomParameters({
      // Optional "tenant" parameter in case you are using an Azure AD tenant.
      // eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or 'contoso.onmicrosoft.com'
      // or "common" for tenant-independent tokens.
      // The default value is "common".
      tenant: 'TENANT_ID'
    });

    Web namespaced API

    provider.setCustomParameters({
      // Optional "tenant" parameter in case you are using an Azure AD tenant.
      // eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or 'contoso.onmicrosoft.com'
      // or "common" for tenant-independent tokens.
      // The default value is "common".
      tenant: 'TENANT_ID'
    });
  3. 選用:指定您想要從身分驗證提供者要求的基本設定檔以外的其他 OAuth 2.0 範圍。

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

    要了解更多信息,請參閱Microsoft 權限和同意文件

  4. 使用 OAuth 提供者物件透過 Firebase 進行身份驗證。您可以透過開啟彈出視窗或重定向到登入頁面來提示使用者使用其 Microsoft 帳戶登入。重定向方法在行動裝置上是首選。

    • 若要使用彈出視窗登錄,請呼叫signInWithPopup

    Web modular API

    import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
    
    const auth = getAuth();
    signInWithPopup(auth, provider)
      .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 namespaced 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.
      });
    • 若要透過重定向到登錄頁面來登錄,請呼叫signInWithRedirect

    使用signInWithRedirectlinkWithRedirectreauthenticateWithRedirect時請遵循最佳實務

    Web modular API

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

    Web namespaced API

    firebase.auth().signInWithRedirect(provider);

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

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

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

    使用 OAuth 存取令牌,您可以呼叫Microsoft Graph API

    例如,要取得基本的個人資料信息,可以呼叫以下REST API:

    curl -i -H "Authorization: Bearer ACCESS_TOKEN" https://graph.microsoft.com/v1.0/me
    

    與 Firebase Auth 支援的其他提供者不同,Microsoft 不提供照片 URL,而是必須透過Microsoft Graph API請求個人資料照片的二進位資料。

    除了 OAuth 存取權杖之外,還可以從firebase.auth.UserCredential物件檢索使用者的 OAuth ID 令牌。 ID 令牌中的sub宣告是特定於應用程式的,與 Firebase Auth 使用的聯合使用者識別碼不匹配,可透過user.providerData[0].uid存取。應改用oid聲明字段。使用 Azure AD 租用戶登入時, oid宣告將完全符合。然而,對於非租戶情況, oid欄位被填入。對於聯合 ID 4b2eabcdefghijkloid的格式為00000000-0000-0000-4b2e-abcdefghijkl

  5. 雖然上面的範例重點介紹登入流程,但您也可以使用linkWithPopup / linkWithRedirect將 Microsoft 提供者連結到現有使用者。例如,您可以將多個提供者連結到同一用戶,允許他們使用其中任一提供者登入。

    Web modular API

    import { getAuth, linkWithPopup, OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('microsoft.com');
    const auth = getAuth();
    
    linkWithPopup(auth.currentUser, provider)
        .then((result) => {
          // Microsoft 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.
        });

    Web namespaced API

    var provider = new firebase.auth.OAuthProvider('microsoft.com');
    firebase.auth().currentUser.linkWithPopup(provider)
        .then((result) => {
          // Microsoft credential is linked to the current user.
          // IdP data available in result.additionalUserInfo.profile.
          // OAuth access token can also be retrieved:
          // result.credential.accessToken
          // OAuth ID token can also be retrieved:
          // result.credential.idToken
        })
        .catch((error) => {
          // Handle error.
        });
  6. 相同的模式可以與reauthenticateWithPopup / reauthenticateWithRedirect一起使用,它可用於檢索需要最近登入的敏感操作的新憑證。

    Web modular API

    import { getAuth, reauthenticateWithPopup, OAuthProvider } from "firebase/auth";
    
    const provider = new OAuthProvider('microsoft.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.
        });

    Web namespaced API

    var provider = new firebase.auth.OAuthProvider('microsoft.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.
          // OAuth access token can also be retrieved:
          // result.credential.accessToken
          // OAuth ID token can also be retrieved:
          // result.credential.idToken
        })
        .catch((error) => {
          // Handle error.
        });

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

如果您正在建立 Chrome 擴充功能應用程序,請參閱Offscreen Documents 指南

下一步

使用者首次登入後,系統會建立新的使用者帳戶,並將其連結到使用者登入時所使用的憑證(即使用者名稱和密碼、電話號碼或驗證提供者資訊)。此新帳戶將作為 Firebase 專案的一部分存儲,並且可用於識別專案中每個應用程式中的用戶,無論用戶如何登入。

  • 在您的應用程式中,了解使用者身份驗證狀態的建議方法是在Auth物件上設定觀察者。然後,您可以從User物件中取得使用者的基本個人資料資訊。請參閱管理用戶

  • 在 Firebase 即時資料庫和雲端儲存安全性規則中,您可以從auth變數取得登入使用者的唯一使用者 ID,並使用它來控制使用者可以存取哪些資料。

您可以透過將身分驗證提供者憑證連結到現有使用者帳戶,允許使用者使用多個驗證提供者登入您的應用程式。

若要登出用戶,請呼叫signOut

Web modular API

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

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

Web namespaced API

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