Authenticate Using Microsoft with JavaScript

You can let your users authenticate with Firebase using OAuth providers likeMicrosoft Azure Active Directory by integrating generic OAuth Logininto your app using the Firebase SDK to carry out the end to end sign-in flow.

Before you begin

To sign in users using Microsoft accounts (Azure Active Directory and personalMicrosoft accounts), you must first enable Microsoft as a sign-in provider foryour Firebase project:

  1. Add Firebase to your JavaScript project.
  2. In theFirebase console, open theAuth section.
  3. On theSign in method tab, enable theMicrosoft provider.
  4. Add theClient ID andClient Secret from that provider's developer console to the provider configuration:
    1. To register a Microsoft OAuth client, follow the instructions in Quickstart: Register an app with the Azure Active Directory v2.0 endpoint. Note that this endpoint supports sign-in using Microsoft personal accounts as well as Azure Active Directory accounts.Learn more about Azure Active Directory v2.0.
    2. When registering apps with these providers, be sure to register the*.firebaseapp.com domain for your project as the redirect domain for your app.
  5. ClickSave.

Handle the sign-in flow with the Firebase SDK

If you are building a web app, the easiest way to authenticate your users withFirebase using their Microsoft accounts is to handle the entire sign-in flowwith the Firebase JavaScript SDK.

To handle the sign-in flow with the Firebase JavaScript SDK, follow these steps:

  1. Create an instance of anOAuthProvider using the provider IDmicrosoft.com.

    Web

    import{OAuthProvider}from"firebase/auth";constprovider=newOAuthProvider('microsoft.com');

    Web

    varprovider=newfirebase.auth.OAuthProvider('microsoft.com');
  2. Optional: Specify additional custom OAuth parameters that you want tosend with the OAuth request.

    Web

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

    Web

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

    For the parameters Microsoft supports, see theMicrosoft OAuth documentation.Note that you can't pass Firebase-required parameters withsetCustomParameters(). These parameters areclient_id,response_type,redirect_uri,state,scope andresponse_mode.

    To allow only users from a particular Azure AD tenant to signinto the application, either the friendly domain name of the Azure AD tenantor the tenant's GUID identifier can be used. This can be done by specifyingthe "tenant" field in the custom parameters object.

    Web

    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

    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. Optional: Specify additional OAuth 2.0 scopes beyond basic profile thatyou want to request from the authentication provider.

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

    To learn more, refer to theMicrosoft permissions and consent documentation.

  4. Authenticate with Firebase using the OAuth provider object. You can promptyour users to sign in with their Microsoft Accounts either by opening apop-up window or by redirecting to the sign-in page. The redirect method ispreferred on mobile devices.

    • To sign in with a pop-up window, callsignInWithPopup:

    Web

    import{getAuth,signInWithPopup,OAuthProvider}from"firebase/auth";constauth=getAuth();signInWithPopup(auth,provider).then((result)=>{// User is signed in.// IdP data available in result.additionalUserInfo.profile.// Get the OAuth access token and ID Tokenconstcredential=OAuthProvider.credentialFromResult(result);constaccessToken=credential.accessToken;constidToken=credential.idToken;}).catch((error)=>{// Handle error.});

    Web

    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.});
    • To sign in by redirecting to the sign-in page, callsignInWithRedirect:

    Follow thebest practices when usingsignInWithRedirect,linkWithRedirect, orreauthenticateWithRedirect.

    Web

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

    Web

    firebase.auth().signInWithRedirect(provider);

    After the user completes sign-in and returns to the page, you can obtain the sign-in result by callinggetRedirectResult.

    Web

    import{getAuth,getRedirectResult,OAuthProvider}from"firebase/auth";constauth=getAuth();getRedirectResult(auth).then((result)=>{// User is signed in.// IdP data available in result.additionalUserInfo.profile.// Get the OAuth access token and ID Tokenconstcredential=OAuthProvider.credentialFromResult(result);constaccessToken=credential.accessToken;constidToken=credential.idToken;}).catch((error)=>{// Handle error.});

    Web

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

    On successful completion, the OAuth access token associated with theprovider can be retrieved from thefirebase.auth.UserCredential objectreturned.

    Using the OAuth access token, you can call theMicrosoft Graph API.

    For example, to get the basic profile information, the following REST APIcan be called:

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

    Unlike other providers supported by Firebase Auth, Microsoft does notprovide a photo URL and instead, the binary data for a profile photo has tobe requested viaMicrosoft Graph API.

    In addition to the OAuth access token, the user's OAuthID tokencan also be retrieved from thefirebase.auth.UserCredential object. Thesub claim in the ID token is app-specific and will not match the federateduser identifier used by Firebase Auth and accessible viauser.providerData[0].uid. Theoid claim field should be used instead.When using a Azure AD tenant to sign-in, theoid claim will be an exactmatch.However for the non-tenant case, theoid field is padded. For a federatedID4b2eabcdefghijkl, theoid will have have a form00000000-0000-0000-4b2e-abcdefghijkl.

  5. While the above examples focus on sign-in flows, you also have theability to link a Microsoft provider to an existing user usinglinkWithPopup/linkWithRedirect. For example, you can link multipleproviders to the same user allowing them to sign in with either.

    Web

    import{getAuth,linkWithPopup,OAuthProvider}from"firebase/auth";constprovider=newOAuthProvider('microsoft.com');constauth=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 Tokenconstcredential=OAuthProvider.credentialFromResult(result);constaccessToken=credential.accessToken;constidToken=credential.idToken;}).catch((error)=>{// Handle error.});

    Web

    varprovider=newfirebase.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. The same pattern can be used withreauthenticateWithPopup/reauthenticateWithRedirect which can be used toretrieve fresh credentials for sensitive operations that require recentlogin.

    Web

    import{getAuth,reauthenticateWithPopup,OAuthProvider}from"firebase/auth";constprovider=newOAuthProvider('microsoft.com');constauth=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 Tokenconstcredential=OAuthProvider.credentialFromResult(result);constaccessToken=credential.accessToken;constidToken=credential.idToken;}).catch((error)=>{// Handle error.});

    Web

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

Handling account-exists-with-different-credential Errors

If you enabled theOne account per email address setting in theFirebase console,when a user tries to sign in a to a provider (such as Microsoft) with an email that alreadyexists for another Firebase user's provider (such as Google), the errorauth/account-exists-with-different-credential is thrown along with anAuthCredential object (Microsoft credential). To complete the sign in to theintended provider, the user has to sign first to the existing provider (Google) and then link to theformerAuthCredential (Microsoft credential).

Popup mode

If you usesignInWithPopup, you can handleauth/account-exists-with-different-credential errors with code like the followingexample:

import{getAuth,linkWithCredential,signInWithPopup,OAuthProvider,}from"firebase/auth";try{//Step1:UsertriestosigninusingMicrosoft.letresult=awaitsignInWithPopup(getAuth(),newOAuthProvider());}catch(error){//Step2:User's email already exists.if(error.code==="auth/account-exists-with-different-credential"){//ThependingMicrosoftcredential.letpendingCred=error.credential;//Step3:Savethependingcredentialintemporarystorage,//Step4:Lettheuserknowthattheyalreadyhaveanaccount//butwithadifferentprovider,andletthemchooseanother//sign-inmethod.}}//...try{//Step5:Signtheuserinusingtheirchosenmethod.letresult=awaitsignInWithPopup(getAuth(),userSelectedProvider);//Step6:LinktotheMicrosoftcredential.//TODO:implement`retrievePendingCred`foryourapp.letpendingCred=retrievePendingCred();if(pendingCred!==null){//Asyouhaveaccesstothependingcredential,youcandirectlycallthe//linkmethod.letuser=awaitlinkWithCredential(result.user,pendingCred);}//Step7:Continuetoapp.}catch(error){//...}

Redirect mode

This error is handled in a similar way in the redirect mode, with the difference that the pendingcredential has to be cached between page redirects (for example, using session storage).

Advanced: Handle the sign-in flow manually

Unlike other OAuth providers supported by Firebase such as Google, Facebook, and Twitter, where sign-in can directly be achieved with OAuth access token based credentials, Firebase Auth does not support the same capability for providers such as Microsoft due to the inability of the Firebase Auth server to verify the audience of Microsoft OAuth access tokens. This is a critical security requirement and could expose applications and websites to replay attacks where a Microsoft OAuth access token obtained for one project (attacker) can be used to sign in to another project (victim). Instead, Firebase Auth offers the ability to handle the entire OAuth flow and the authorization code exchange using the OAuth client ID and secret configured in the Firebase Console. As the authorization code can only be used in conjunction with a specific client ID/secret, an authorization code obtained for one project cannot be used with another.

If these providers are required to be used in unsupported environments, a third party OAuth library andFirebase custom authentication would need to be used. The former is needed to authenticate with the provider and the latter to exchange the provider’s credential for a custom token.

Authenticate with Firebase in a Chrome extension

If you are building a Chrome extension app, see the Offscreen Documents guide.

Customizing the redirect domain for Microsoft sign-in

On project creation, Firebase will provision a unique subdomain for your project:https://my-app-12345.firebaseapp.com.

This will also be used as the redirect mechanism for OAuth sign in. That domain would need to be allowed for all supported OAuth providers. However, this means that users may see that domain while signing in to Microsoft before redirecting back to the application:Continue to: https://my-app-12345.firebaseapp.com.

To avoid displaying your subdomain, you can set up a custom domain withFirebase Hosting:

  1. Follow steps 1 through 3 inSet up your domain forHosting. When you verify your domain ownership,Hosting provisions an SSL certificate for your custom domain.
  2. Add your custom domain to the list of authorized domains in theFirebase console:auth.custom.domain.com.
  3. In the Microsoft developer console or OAuth setup page, whitelist the URL of the redirect page, which will be accessible on your custom domain:https://auth.custom.domain.com/__/auth/handler.
  4. When you initialize the JavaScript library, specify your custom domain with theauthDomain field:
    varconfig={apiKey:'...',//Changedfrom'PROJECT_ID.firebaseapp.com'.authDomain:'auth.custom.domain.com',databaseURL:'https://PROJECT_ID.firebaseio.com',projectId:'PROJECT_ID',storageBucket:'PROJECT_ID.firebasestorage.app',messagingSenderId:'SENDER_ID'};firebase.initializeApp(config);

Next steps

After a user signs in for the first time, a new user account is created andlinked to the credentials—that is, the user name and password, phonenumber, or auth provider information—the user signed in with. This newaccount is stored as part of your Firebase project, and can be used to identifya user across every app in your project, regardless of how the user signs in.

  • In your apps, the recommended way to know the auth status of your user is toset an observer on theAuth object. You can then get the user'sbasic profile information from theUser object. SeeManage Users.

  • In yourFirebase Realtime Database andCloud StorageSecurity Rules, you can get the signed-in user's unique user ID from theauth variable, and use it to control what data a user can access.

You can allow users to sign in to your app using multiple authenticationproviders bylinking auth provider credentials to anexisting user account.

To sign out a user, callsignOut:

Web

import{getAuth,signOut}from"firebase/auth";constauth=getAuth();signOut(auth).then(()=>{// Sign-out successful.}).catch((error)=>{// An error happened.});

Web

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

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2026-02-05 UTC.