provider.setCustomParameters({// Force re-consent.prompt:'consent',// Target specific email with login hint.login_hint:'user@firstadd.onmicrosoft.com'});
您可以使用 mkt 參數自訂驗證流程的語言。例如:
provider.setCustomParameters({mkt:'fr'});
您可以使用 tenant 屬性,限制特定 Azure AD 網域以外使用者的存取權。請指定用戶群的易記網域名稱或 GUID ID。不在這個網域中的使用者將無法登入。例如:
firebase.auth().signInWithPopup(provider).then((result)=>{// IdP data available in result.additionalUserInfo.profile.// .../** @type {firebase.auth.OAuthCredential} */varcredential=result.credential;// OAuth access and id tokens can also be retrieved:varaccessToken=credential.accessToken;varidToken=credential.idToken;}).catch((error)=>{// Handle error.});
接著,在頁面載入時呼叫 getRedirectResult(),藉此擷取 Microsoft 權杖:
JavaScript
firebase.auth().getRedirectResult().then((result)=>{// IdP data available in result.additionalUserInfo.profile.// .../** @type {firebase.auth.OAuthCredential} */varcredential=result.credential;// OAuth access and id tokens can also be retrieved:varaccessToken=credential.accessToken;varidToken=credential.idToken;}).catch((error)=>{// Handle error.});
與 Identity Platform 支援的其他提供者不同,Microsoft 不會為使用者提供相片網址。您必須改用 Graph API 來要求相片的二進位資料。
除了存取權杖外,您還可以擷取使用者的 Microsoft ID 權杖。這個權杖中的 oid 要求包含使用者的專屬 ID。您可以將此 ID 與位於 user.providerData[0].uid 的 ID 進行比較。如果使用者是透過 Azure AD 用戶群登入,這些欄位會完全相符。如果不是,欄位會以零填補 (例如聯盟 ID 4b2eabcdefghijkl 會顯示為 00000000-0000-0000-4b2e-abcdefghijkl)。
請勿使用 sub 聲明來比較使用者 ID。sub 宣告是特定應用程式專屬,與 Microsoft 使用的 ID 不符。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-04 (世界標準時間)。"],[[["\u003cp\u003eThis guide outlines the process of configuring and using Microsoft as an identity provider within Identity Platform, supporting both personal Microsoft accounts and Azure AD accounts.\u003c/p\u003e\n"],["\u003cp\u003eSetting up Microsoft as a provider requires obtaining an App ID and App Secret from Azure AD, and configuring a valid OAuth redirect URI in the Microsoft app settings.\u003c/p\u003e\n"],["\u003cp\u003eThe client SDK facilitates user sign-in through the creation of an \u003ccode\u003eOAuthProvider\u003c/code\u003e object, and can include optional OAuth scopes and custom parameters to enhance authentication and data access.\u003c/p\u003e\n"],["\u003cp\u003eUsers can sign in either through a pop-up window with \u003ccode\u003esignInWithPopup()\u003c/code\u003e or by redirecting the page with \u003ccode\u003esignInWithRedirect()\u003c/code\u003e, both of which return data and tokens from Microsoft upon successful sign in.\u003c/p\u003e\n"],["\u003cp\u003eUnlike some other providers, manual sign-in with Microsoft through \u003ccode\u003esignInWithCredential()\u003c/code\u003e is not supported due to security requirements, and alternative options like custom authentication with third-party OAuth libraries are available for those that can't use the SDK.\u003c/p\u003e\n"]]],[],null,["# Signing in users with Microsoft\n===============================\n\nThis document shows you how to use Identity Platform to sign in users with\nMicrosoft. Both personal Microsoft accounts and Azure Active Directory\n(Azure AD) accounts are supported.\n\nBefore you begin\n----------------\n\nThis tutorial assumes you've already enabled Identity Platform, and have a\nbasic web app written using HTML and JavaScript. See the\n[Quickstart](/identity-platform/docs/sign-in-user-email) to learn how.\n\nConfiguring Microsoft as a provider\n-----------------------------------\n\nTo configure Microsoft as an identity provider:\n\n1. Go to the **Identity Providers** page in the Google Cloud console.\n\n [Go to the Identity Providers page](https://console.cloud.google.com/customer-identity/providers)\n2. Click **Add A Provider**.\n\n3. Select **Microsoft** from the list.\n\n4. Enter your Microsoft **App ID** and **App Secret** . If\n you don't already have an ID and secret, follow the steps in\n [Quickstart: Register an app with the Azure AD v2.0 endpoint](https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app)\n to obtain one.\n\n This endpoint supports both personal Microsoft accounts and Azure AD\n accounts. See the\n [Microsoft identity platform (v2.0) overview](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-overview)\n to learn more about Azure AD.\n5. Configure the URI listed under **Configure Microsoft** as the valid OAuth\n redirect URI for your Microsoft app. If you configured a custom domain in Identity Platform,\n update the redirect URI in your Microsoft app configuration to use the custom domain instead\n of the default domain. For example, change `https://myproject.firebaseapp.com/__/auth/handler` to\n `https://auth.myownpersonaldomain.com/__/auth/handler`.\n\n6. Register your app's domains by clicking **Add Domain** under\n **Authorized Domains** . For development purposes, `localhost` is already\n enabled by default.\n\n | **Important:** In projects created after April 28, 2025, Identity Platform no longer includes `localhost` as an authorized domain by default. Google strongly discourages the use of `localhost` in production projects. If you choose to authorize `localhost`, you can manually add it in the **Settings** page, in **Authorized Domains** , by clicking **Add Domain**.\n7. Under **Configure your application** , click **Setup Details**. Copy the\n snippet into your app's code to initialize the Identity Platform\n client SDK.\n\n8. Click **Save**.\n\nSigning in users with the client SDK\n------------------------------------\n\n1. Create an instance of the `OAuthProvider` object, passing `microsoft.com` as\n the provider ID:\n\n ### JavaScript\n\n\n ```javascript\n var provider = new firebase.auth.OAuthProvider('microsoft.com');https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/auth/microsoft-oauth.js#L11-L11\n ```\n\n \u003cbr /\u003e\n\n2. **Optional:** Add OAuth scopes. Scopes specify what data you are\n requesting from Microsoft. More sensitive data may require specific\n scopes. Consult Microsoft's\n [documentation](https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent)\n to determine what scopes your app needs.\n\n ### JavaScript\n\n provider.addScope('mail.read');\n provider.addScope('calendars.read');\n\n3. **Optional:** Specify additional custom OAuth parameters. These are\n specific to Microsoft, and are typically used to customize the\n authentication experience.\n\n ### JavaScript\n\n provider.setCustomParameters({\n // Force re-consent.\n prompt: 'consent',\n // Target specific email with login hint.\n login_hint: 'user@firstadd.onmicrosoft.com'\n });\n\n You can use the `mkt` parameter to customize the language of the\n authentication flow. For example: \n\n provider.setCustomParameters({\n mkt: 'fr'\n });\n\n You can use the `tenant` property to limit access to users outside a\n particular Azure AD domain. Specify either the friendly domain name of\n the tenant, or its GUID identifier. Users who are not within this domain\n will not be able to sign in. For example: \n\n provider.setCustomParameters({\n // Optional \"tenant\" parameter in case you are using an Azure AD tenant.\n // eg. '8eaef023-2b34-4da1-9baa-8bc8c9d6a490' or 'contoso.onmicrosoft.com'\n // or \"common\" for tenant-independent tokens.\n // The default value is \"common\".\n tenant: 'TENANT_ID'\n });\n\n See the [Microsoft OAuth documentation](https://docs.microsoft.com/en-us/azure/active-directory/develop/v1-protocols-oauth-code)\n for a full list of parameters Microsoft supports. Note that you can't pass\n parameters reserved by OAuth or Identity Platform.\n4. Use the `OAuthProvider` object to sign in the user. You can either\n open a pop-up window, or redirect the current page. Redirecting is easier\n for users on mobile devices.\n\n To show a pop-up, call `signInWithPopup()`: \n\n ### JavaScript\n\n\n ```javascript\n firebase.auth().signInWithPopup(provider)\n .then((result) =\u003e {\n // IdP data available in result.additionalUserInfo.profile.\n // ...\n\n /** @type {firebase.auth.OAuthCredential} */\n var credential = result.credential;\n\n // OAuth access and id tokens can also be retrieved:\n var accessToken = credential.accessToken;\n var idToken = credential.idToken;\n })\n .catch((error) =\u003e {\n // Handle error.\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/auth/microsoft-oauth.js#L41-L55\n ```\n\n \u003cbr /\u003e\n\n To redirect the page, first call `signInWithRedirect()`:\n\n\n Follow the [best practices](/identity-platform/docs/web/redirect-best-practices) when using `signInWithRedirect`, `linkWithRedirect`, or `reauthenticateWithRedirect`.\n\n\n ### JavaScript\n\n\n ```javascript\n firebase.auth().signInWithRedirect(provider);https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/auth/microsoft-oauth.js#L61-L61\n ```\n\n \u003cbr /\u003e\n\n Then, retrieve the Microsoft token by calling `getRedirectResult()`\n when your page loads: \n\n ### JavaScript\n\n\n ```javascript\n firebase.auth().getRedirectResult()\n .then((result) =\u003e {\n // IdP data available in result.additionalUserInfo.profile.\n // ...\n\n /** @type {firebase.auth.OAuthCredential} */\n var credential = result.credential;\n\n // OAuth access and id tokens can also be retrieved:\n var accessToken = credential.accessToken;\n var idToken = credential.idToken;\n })\n .catch((error) =\u003e {\n // Handle error.\n });https://github.com/firebase/snippets-web/blob/467eaa165dcbd9b3ab15711e76fa52237ba37f8b/auth/microsoft-oauth.js#L67-L81\n ```\n\n \u003cbr /\u003e\n\nOnce you have an access token, you can use it to call the\n[Microsoft Graph API](https://docs.microsoft.com/graph/overview)\nFor example: \n\n### REST\n\n curl -i -H \"Authorization: Bearer [ACCESS_TOKEN]\" https://graph.microsoft.com/v1.0/me\n\nUnlike other providers supported by Identity Platform, Microsoft does not\nprovide a photo URL for users. Instead, you'll need to use the Graph API to\nrequest the binary data for the photo.\n\nIn addition to the access token, you can also retrieve a user's Microsoft\n[ID token](https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens).\nThe `oid` claim on this token contains a unique ID for the user. You can compare\nthis against the ID located at `user.providerData[0].uid`. If your users are\nsigning in with an Azure AD tenant, these fields will match exactly. If they\naren't, the field will be padded with zeroes (for example, the federated ID\n`4b2eabcdefghijkl` will appear as `00000000-0000-0000-4b2e-abcdefghijkl`).\n\nDo not use the `sub` claim to compare user IDs. The `sub` claim is app-specific,\nand will not match the ID used by Microsoft.\n\nSigning in users manually\n-------------------------\n\nSome other Identity Platform providers, such as\n[Google](/identity-platform/docs/web/google),\n[Facebook](/identity-platform/docs/web/facebook), and\n[Twitter](/identity-platform/docs/web/twitter), allow you to sign in users\nmanually by calling `signInWithCredential()`.\n\nThis capability is not supported for Microsoft. Identity Platform is not\nable to verify the audience of Microsoft OAuth access tokens, which is a\ncritical security requirement.\n\nIf you can't use the Identity Platform client SDK to sign in users,\nyou'll need to use a third-party OAuth library to authenticate with Microsoft.\nYou can then use [Custom authentication](/identity-platform/docs/web/custom) to\nexchange the Microsoft credential for a custom token.\n\nWhat's next\n-----------\n\n- Learn more about [Identity Platform users](/identity-platform/docs/concepts-manage-users).\n- Sign in users with [other identity providers](/identity-platform/docs/how-to#signing-in-users)."]]