您可以使用 Firebase SDK 將通用 OAuth 登入功能整合至應用程式,藉此讓使用者透過 Microsoft Azure Active Directory 等 OAuth 供應商驗證 Firebase,並執行端對端登入流程。
事前準備
如要讓使用者使用 Microsoft 帳戶 (Azure Active Directory 和個人 Microsoft 帳戶) 登入,您必須先將 Microsoft 設為 Firebase 專案的登入提供者:
- 將 Firebase 新增至 JavaScript 專案。
- 在 Firebase 控制台中,開啟「Auth」部分。
- 在「Sign in method」分頁中,啟用 Microsoft 供應器。
- 將該供應商開發人員工作室的「用戶端 ID」和「用戶端密鑰」新增至供應商設定:
- 如要註冊 Microsoft OAuth 用戶端,請按照 快速入門:使用 Azure Active Directory 2.0 端點註冊應用程式中的指示操作。請注意,這個端點支援使用 Microsoft 個人帳戶和 Azure Active Directory 帳戶登入。進一步瞭解 Azure Active Directory 2.0 版。
- 向這些供應商註冊應用程式時,請務必將專案的
*.firebaseapp.com
網域註冊為應用程式的重新導向網域。
- 按一下 [儲存]。
使用 Firebase SDK 處理登入流程
如果您要建構網頁應用程式,透過 Firebase 驗證使用者是否使用 Microsoft 帳戶,最簡單的方法就是使用 Firebase JavaScript SDK 處理整個登入流程。
如要使用 Firebase JavaScript SDK 處理登入流程,請按照下列步驟操作:
使用提供者 ID microsoft.com 建立 OAuthProvider 例項。
import { OAuthProvider } from "firebase/auth"; const provider = new OAuthProvider('microsoft.com');
var provider = new firebase.auth.OAuthProvider('microsoft.com');
選用:指定您要透過 OAuth 要求傳送的其他自訂 OAuth 參數。
provider.setCustomParameters({ // Force re-consent. prompt: 'consent', // Target specific email with login hint. login_hint: 'user@firstadd.onmicrosoft.com' });
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_id、response_type、redirect_uri、state、scope 和 response_mode。如要只允許特定 Azure AD 用戶群的使用者登入應用程式,您可以使用 Azure AD 用戶群的易記網域名稱或用戶群的 GUID ID。如要執行這項操作,請在自訂參數物件中指定「tenant」欄位。
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' });
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' });
選用:指定您要向驗證服務供應器要求的其他 OAuth 2.0 範圍 (除了基本設定檔)。
provider.addScope('mail.read'); provider.addScope('calendars.read');
詳情請參閱 Microsoft 權限和同意聲明說明文件。
使用 OAuth 提供者物件與 Firebase 進行驗證。您可以開啟彈出式視窗或重新導向至登入頁面,提示使用者使用 Microsoft 帳戶登入。在行動裝置上,建議使用重新導向方法。
- 如要透過彈出式視窗登入,請呼叫
signInWithPopup
:
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. });
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
:
使用
signInWithRedirect
、linkWithRedirect
或reauthenticateWithRedirect
時,請遵循最佳做法。import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
firebase.auth().signInWithRedirect(provider);
使用者完成登入並返回頁面後,您可以呼叫
getRedirectResult
取得登入結果。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. });
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 不會提供相片網址,而是必須透過 Microsoft Graph API 要求個人資料相片的二進位資料。
除了 OAuth 存取權杖外,您也可以從
firebase.auth.UserCredential
物件擷取使用者的 OAuth ID 權杖。ID 權杖中的sub
憑證是特定於應用程式,不會與 Firebase 驗證所使用的聯合使用者 ID 相符,且可透過user.providerData[0].uid
存取。請改用oid
宣告欄位。使用 Azure AD 用戶群登入時,oid
權杖會完全相符。不過,如果是未分租的情況,oid
欄位會加上填充字元。對於聯合 ID4b2eabcdefghijkl
,oid
會採用00000000-0000-0000-4b2e-abcdefghijkl
的形式。- 如要透過彈出式視窗登入,請呼叫
雖然上述範例著重於登入流程,但您也可以使用
linkWithPopup
/linkWithRedirect
將 Microsoft 供應器連結至現有使用者。舉例來說,您可以將多個供應器連結至同一位使用者,讓他們可以使用任一供應器登入。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. });
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. });
reauthenticateWithPopup
/reauthenticateWithRedirect
可使用相同的模式,可用於擷取敏感作業的最新憑證,這些作業需要最近的登入作業。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. });
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. });
處理「account-exists-with-different-credential」錯誤
如果您在 Firebase 主控台中啟用「每個電子郵件地址只能建立一個帳戶」設定,當使用者嘗試使用另一個 Firebase 使用者 (例如 Google) 提供者的電子郵件地址 (已存在於其他提供者,例如 Microsoft) 登入時,系統會擲回錯誤 auth/account-exists-with-different-credential
和 AuthCredential
物件 (Microsoft 憑證)。如要完成登入指定提供者的程序,使用者必須先登入現有提供者 (Google),然後連結至前 AuthCredential
(Microsoft 憑證)。
彈出式模式
如果您使用 signInWithPopup
,可以使用以下程式碼處理 auth/account-exists-with-different-credential
錯誤:
import { getAuth, linkWithCredential, signInWithPopup, OAuthProvider, } from "firebase/auth"; try { // Step 1: User tries to sign in using Microsoft. 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 Microsoft 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 Microsoft 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 驗證無法為 Microsoft 等供應商提供相同功能,因為 Firebase 驗證伺服器無法驗證 Microsoft OAuth 存取權權杖的目標對象。這是一項重要的安全性規定,如果應用程式和網站遭到重播攻擊,攻擊者可利用為某個專案 (攻擊者) 取得的 Microsoft OAuth 存取權權杖,登入另一個專案 (受害者)。相反地,Firebase Auth 可使用 Firebase 主控台中設定的 OAuth 用戶端 ID 和秘密,處理整個 OAuth 流程和授權碼交換作業。由於授權碼只能與特定用戶端 ID/密鑰搭配使用,因此為某個專案取得的授權碼無法用於其他專案。
如果您需要在未支援的環境中使用這些提供者,就必須使用第三方 OAuth 程式庫和 Firebase 自訂驗證。前者用於與供應商進行驗證,後者則用於交換供應商的憑證,以取得自訂權杖。
在 Chrome 擴充功能中使用 Firebase 進行驗證
如果您要建構 Chrome 擴充功能應用程式,請參閱 離線文件指南。
自訂 Microsoft 登入的重新導向網域
建立專案時,Firebase 會為您的專案提供專屬子網域:https://my-app-12345.firebaseapp.com
。
這也會用來做為 OAuth 登入的重新導向機制。您必須為所有支援的 OAuth 供應商允許該網域。不過,這也表示使用者在登入 Microsoft 時,可能會看到以下網域,然後再重新導向至應用程式:繼續前往:https://my-app-12345.firebaseapp.com。
如要避免顯示子網域,您可以使用 Firebase Hosting 設定自訂網域:
- 請按照「為 Hosting 設定網域」中的步驟 1 至 3 操作。驗證網域擁有權後,Hosting 會為自訂網域佈建 SSL 憑證。
- 將自訂網域新增至 Firebase 控制台的授權網域清單:
auth.custom.domain.com
。 - 在 Microsoft 開發人員控制台或 OAuth 設定頁面中,將重新導向網頁的網址加入白名單,這樣您就能透過自訂網域
https://auth.custom.domain.com/__/auth/handler
存取該網頁。 - 初始化 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: ' ', messagingSenderId: 'PROJECT_ID .firebasestorage.appSENDER_ID ' }; firebase.initializeApp(config);
後續步驟
使用者首次登入後,系統會建立新使用者帳戶,並連結至使用者登入時所用的憑證 (即使用者名稱和密碼、電話號碼或驗證服務提供者資訊)。這個新帳戶會儲存在 Firebase 專案中,無論使用者如何登入,都可以用於在專案中的每個應用程式中識別使用者。
-
在應用程式中,建議您在
Auth
物件上設定觀察器,以便瞭解使用者的驗證狀態。接著,您可以從User
物件取得使用者的基本個人資料資訊。請參閱「管理使用者」。 在 Firebase Realtime Database 和 Cloud Storage 安全性規則中,您可以從
auth
變數取得已登入使用者的專屬使用者 ID,並利用該 ID 控管使用者可存取的資料。
您可以將驗證服務供應商憑證連結至現有使用者帳戶,讓使用者使用多個驗證服務供應商登入應用程式。
如要將使用者登出,請呼叫
signOut
:
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. });