Authenticate Using Microsoft with JavaScript

You can let your users authenticate with Firebase using OAuth providers like
Microsoft Azure Active Directory by integrating generic OAuth Login
into 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 personal
Microsoft accounts), you must first enable Microsoft as a sign-in provider for
your Firebase project:

For the parameters Microsoft supports, see the
Microsoft OAuth documentation.
Note that you can't pass Firebase-required parameters with
setCustomParameters(). These parameters are client_id,
response_type, redirect_uri, state, scope and
response_mode.

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

Authenticate with Firebase using the OAuth provider object. You can prompt
your users to sign in with their Microsoft Accounts either by opening a
pop-up window or by redirecting to the sign-in page. The redirect method is
preferred on mobile devices.

Unlike other providers supported by Firebase Auth, Microsoft does not
provide a photo URL and instead, the binary data for a profile photo has to
be requested via
Microsoft Graph API.

While the above examples focus on sign-in flows, you also have the
ability to link a Microsoft provider to an existing user using
linkWithPopup/linkWithRedirect. For example, you can link multiple
providers to the same user allowing them to sign in with either.

Handling account-exists-with-different-credential Errors

If you enabled the One account per email address setting in the Firebase console,
when a user tries to sign in a to a provider (such as Microsoft) with an email that already
exists for another Firebase user's provider (such as Google), the error
auth/account-exists-with-different-credential is thrown along with an
AuthCredential object (Microsoft credential). To complete the sign in to the
intended provider, the user has to sign first to the existing provider (Google) and then link to the
former AuthCredential (Microsoft credential).

Popup mode

If you use signInWithPopup, you can handle
auth/account-exists-with-different-credential errors with code like the following
example:

// Step 1.
// User tries to sign in to Microsoft.
auth.signInWithPopup(new firebase.auth.OAuthProvider('microsoft.com')).catch(function(error) {
// An error happened.
if (error.code === 'auth/account-exists-with-different-credential') {
// Step 2.
// User's email already exists.
// The pending Microsoft credential.
var pendingCred = error.credential;
// The provider account's email address.
var email = error.email;
// Get sign-in methods for this email.
auth.fetchSignInMethodsForEmail(email).then(function(methods) {
// Step 3.
// If the user has several sign-in methods,
// the first method in the list will be the "recommended" method to use.
if (methods[0] === 'password') {
// Asks the user their password.
// In real scenario, you should handle this asynchronously.
var password = promptUserForPassword(); // TODO: implement promptUserForPassword.
auth.signInWithEmailAndPassword(email, password).then(function(user) {
// Step 4a.
return user.linkWithCredential(pendingCred);
}).then(function() {
// Microsoft account successfully linked to the existing Firebase user.
goToApp();
});
return;
}
// All the other cases are external providers.
// Construct provider object for that provider.
// TODO: implement getProviderForProviderId.
var provider = getProviderForProviderId(methods[0]);
// At this point, you should let the user know that he already has an account
// but with a different provider, and let him validate the fact he wants to
// sign in with this provider.
// Sign in to provider. Note: browsers usually block popup triggered asynchronously,
// so in real scenario you should ask the user to click on a "continue" button
// that will trigger the signInWithPopup.
auth.signInWithPopup(provider).then(function(result) {
// Remember that the user may have signed in with an account that has a different email
// address than the first one. This can happen as Firebase doesn't control the provider's
// sign in flow and the user is free to login using whichever account he owns.
// Step 4b.
// Link to Microsoft credential.
// As we have access to the pending credential, we can directly call the link method.
result.user.linkAndRetrieveDataWithCredential(pendingCred).then(function(usercred) {
// Microsoft account successfully linked to the existing Firebase user.
goToApp();
});
});
});
}
});

Redirect mode

This error is handled in a similar way in the redirect mode, with the difference that the pending
credential 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 and
Firebase 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, you must whitelist your Chrome extension ID:

Only popup operations (signInWithPopup and linkWithPopup) are available
to Chrome extensions, as Chrome extensions cannot use HTTP redirects. You should call these methods
from a background script rather than a browser action popup, as the authentication popup will cancel
the browser action popup.

In your Chrome extension's manifest file make sure that you add the
https://apis.google.com URL to the content_security_policy whitelist.

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
whitelisted 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 customize the URL in the message to show a custom domain:
Continue to: https://auth.custom.domain.com

Create a CNAME record for your custom domain that points to your project's subdomain on
firebaseapp.com:

auth.custom.domain.com CNAME my-app-12345.firebaseapp.com

Add your custom domain to the list of authorized domains in the
Firebase console: auth.custom.domain.com.

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.

When you initialize the JavaScript library, specify your custom domain with the
authDomain field:

Next steps

After a user signs in for the first time, a new user account is created and
linked to the credentials—that is, the user name and password, phone
number, or auth provider information—the user signed in with. This new
account is stored as part of your Firebase project, and can be used to identify
a 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 to
set an observer on the Auth object. You can then get the user's
basic profile information from the User object. See
Manage Users.

In your Firebase Realtime Database and Cloud Storage
Security Rules, you can
get the signed-in user's unique user ID from the auth variable,
and use it to control what data a user can access.