通過使用 Firebase SDK 將通用 OAuth 登錄集成到您的應用程序中,您可以讓您的用戶使用 OAuth 提供程序(如 Microsoft Azure Active Directory)向 Firebase 進行身份驗證,以執行端到端的登錄流程。
在你開始之前
要使用 Microsoft 帳戶(Azure Active Directory 和個人 Microsoft 帳戶)登錄用戶,您必須首先啟用 Microsoft 作為 Firebase 項目的登錄提供程序:
- 將 Firebase 添加到您的 JavaScript 項目中。
- 在Firebase 控制台中,打開Auth部分。
- 在登錄方法選項卡上,啟用Microsoft提供程序。
- 將該提供者的開發者控制台中的客戶端 ID和客戶端密碼添加到提供者配置中:
- 要註冊 Microsoft OAuth 客戶端,請按照快速入門:使用 Azure Active Directory v2.0 端點註冊應用中的說明進行操作。請注意,此終結點支持使用 Microsoft 個人帳戶以及 Azure Active Directory 帳戶登錄。詳細了解 Azure Active Directory v2.0。
- 向這些提供商註冊應用程序時,請務必將項目的
*.firebaseapp.com
域註冊為應用程序的重定向域。
- 單擊保存。
使用 Firebase SDK 處理登錄流程
如果您正在構建一個 Web 應用程序,使用他們的 Microsoft 帳戶通過 Firebase 對您的用戶進行身份驗證的最簡單方法是使用 Firebase JavaScript SDK 處理整個登錄流程。
要使用 Firebase JavaScript SDK 處理登錄流程,請按以下步驟操作:
使用提供程序 ID microsoft.com創建OAuthProvider的實例。
Web version 9
import { OAuthProvider } from "firebase/auth"; const provider = new OAuthProvider('microsoft.com');
Web version 8
var provider = new firebase.auth.OAuthProvider('microsoft.com');
可選:指定要隨 OAuth 請求一起發送的其他自定義 OAuth 參數。
Web version 9
provider.setCustomParameters({ // Force re-consent. prompt: 'consent', // Target specific email with login hint. login_hint: 'user@firstadd.onmicrosoft.com' });
Web version 8
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 標識符。這可以通過在自定義參數對像中指定“租戶”字段來完成。
Web version 9
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 version 8
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
:
Web version 9
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 version 8
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
:
Web version 9
import { getAuth, signInWithRedirect } from "firebase/auth"; const auth = getAuth(); signInWithRedirect(auth, provider);
Web version 8
firebase.auth().signInWithRedirect(provider);
用戶完成登錄並返回頁面後,可以通過調用
getRedirectResult
獲取登錄結果。Web version 9
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 version 8
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
字段被填充。對於聯合 ID4b2eabcdefghijkl
,oid
的格式為00000000-0000-0000-4b2e-abcdefghijkl
。- 要使用彈出窗口登錄,請調用
雖然上述示例側重於登錄流程,但您還可以使用
linkWithPopup
/linkWithRedirect
將 Microsoft 提供程序鏈接到現有用戶。例如,您可以將多個提供商鏈接到同一個用戶,允許他們使用其中任何一個登錄。Web version 9
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 version 8
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
一起使用,可用於檢索需要最近登錄的敏感操作的新憑據。Web version 9
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 version 8
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 擴展應用程序,則必須添加您的 Chrome 擴展 ID:
- 在Firebase 控制台中打開您的項目。
- 在身份驗證部分中,打開登錄方法頁面。
- 將如下所示的 URI 添加到授權域列表中:
chrome-extension://CHROME_EXTENSION_ID
Chrome 擴展程序只能使用彈出操作( signInWithPopup
、 linkWithPopup
和reauthenticateWithPopup
),因為 Chrome 擴展程序不能使用 HTTP 重定向。您應該從後台頁面腳本而不是瀏覽器操作彈出窗口調用這些方法,因為身份驗證彈出窗口將取消瀏覽器操作彈出窗口。彈出方法只能用於使用Manifest V2的擴展。較新的Manifest V3只允許服務工作者形式的後台腳本,根本無法執行彈出操作。
在 Chrome 擴展程序的清單文件中,確保將https://apis.google.com
URL 添加到content_security_policy
許可名單。
下一步
用戶首次登錄後,會創建一個新用戶帳戶並將其鏈接到憑據(即用戶名和密碼、電話號碼或身份驗證提供商信息),即用戶登錄時使用的憑據。這個新帳戶作為 Firebase 項目的一部分存儲,可用於在項目中的每個應用中識別用戶,無論用戶如何登錄。
在您的應用程序中,了解用戶身份驗證狀態的推薦方法是在
Auth
對像上設置觀察者。然後,您可以從User
對像中獲取用戶的基本配置文件信息。請參閱管理用戶。在您的 Firebase 實時數據庫和雲存儲安全規則中,您可以從
auth
變量中獲取登錄用戶的唯一用戶 ID,並使用它來控制用戶可以訪問哪些數據。
您可以通過將身份驗證提供程序憑據鏈接到現有用戶帳戶來允許用戶使用多個身份驗證提供程序登錄您的應用程序。
要註銷用戶,請調用signOut
:
Web version 9
import { getAuth, signOut } from "firebase/auth"; const auth = getAuth(); signOut(auth).then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });
Web version 8
firebase.auth().signOut().then(() => { // Sign-out successful. }).catch((error) => { // An error happened. });