Vanilla JavaScript single-page application (SPA) using MSAL.js to authenticate users against Azure AD B2C
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- More information
- Community Help and Support
This sample demonstrates a Vanilla JavaScript single-page application (SPA) that lets users sign-in with Azure Active Directory B2C using the Microsoft Authentication Library for JavaScript) (MSAL.js). In doing so, it also illustrates various authentication and B2C concepts, such as ID tokens, external identity providers , consumer social accounts, single-sign on (SSO), account selection, silent requests and more.
- The client application uses MSAL.js to obtain an ID Token from Azure AD B2C.
- The ID Token proves that the user has successfully authenticated against Azure AD B2C.
File/folder | Description |
---|---|
App/authPopup.js |
Main authentication logic resides here (using popup flow). |
App/authRedirect.js |
Use this instead of authPopup.js for authentication with redirect flow. |
App/authConfig.js |
Contains configuration parameters for the sample. |
App/ui.js |
Contains UI logic. |
server.js |
Simple Node server to index.html . |
- An Azure Active Directory B2C (Azure AD B2C) tenant. For more information, see: Create an Azure Active Directory B2C tenant
- A user account in your Azure AD B2C tenant.
From your shell or command line:
git clone https://github.com/Azure-Samples/ms-identity-javascript-tutorial.git
or download and extract the repository .zip file.
⚠️ To avoid path length limitations on Windows, we recommend cloning into a directory near the root of your drive.
Locate the sample folder, then type:
npm install
As a first step you'll need to:
- Sign in to the Azure portal.
- If your account is present in more than one Azure AD B2C tenant, select your profile at the top right corner in the menu on top of the page, and then switch directory to change your portal session to the desired Azure AD B2C tenant.
If you don't have an Azure AD B2C tenant yet, please see: Tutorial: Create an Azure Active Directory B2C tenant.
- Navigate to the Microsoft identity platform for developers App registrations page.
- Select New registration.
- In the Register an application page that appears, enter your application's registration information:
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
ms-identity-javascript-c1s2-spa
. - Under Supported account types, select Accounts in any organizational directory or any identity provider. For authenticating users with Azure AD B2C.
- In the Redirect URI (optional) section, select Single-Page Application in the combo-box and enter the following redirect URI:
http://localhost:6420/
.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- Select Register to create the application.
- In the app's registration screen, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
- Select Save to save your changes.
Please refer to: Tutorial: Create user flows in Azure Active Directory B2C
Please refer to: Tutorial: Add identity providers to your applications in Azure Active Directory B2C
Open the project in your IDE (like Visual Studio or Visual Studio Code) to configure the code.
In the steps below, "ClientID" is the same as "Application ID" or "AppId".
Open the App\authConfig.js
file. Then:
- Find the key
clientId
and replace the existing value with the application ID (clientId) of thems-identity-javascript-c1s2-spa
application copied from the Azure portal. - Find the key
redirectUri
and replace the existing value with the base address of thems-identity-javascript-c1s2-spa
app (by defaulthttp://localhost:6420
). - Find the key
postLogoutRedirectUri
and replace the existing value with the base address of thems-identity-javascript-c1s2-spa
app and the signout page that the app will redirect to e.g.http://localhost:6420/signout
.
Open the App\policies.js
file. Then:
- Find the key
names
and populate it with your policy names e.g.signUpSignIn
. - Find the key
authorities
and populate it with your policy authority strings e.g.https://<your-tenant-name>.b2clogin.com/<your-tenant-name>.onmicrosoft.com/b2c_1_susi
. - Find the key
authorityDomain
and populate it with the domain portion of your authority string e.g.<your-tenant-name>.b2clogin.com
.
Locate the sample folder, then type:
npm start
- Open your browser and navigate to
http://localhost:6420
. - Click on the sign-in button on the top right corner.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
MSAL.js provides 3 login APIs: loginPopup()
, loginRedirect()
and ssoSilent()
:
myMSALObj.loginPopup(loginRequest)
.then((response) => {
// your logic
})
.catch(error => {
console.error(error);
});
To use the redirect flow, you must register a handler for redirect promise. MSAL.js provides handleRedirectPromise()
API:
myMSALObj.handleRedirectPromise()
.then((response) => {
// your logic
})
.catch(err => {
console.error(err);
});
myMSALObj.loginRedirect(loginRequest);
The recommended pattern is that you fallback to an interactive method should the silent SSO fails.
const silentRequest = {
scopes: ["openid", "profile"],
loginHint: "[email protected]"
};
myMSALObj.ssoSilent(silentRequest)
.then((response) => {
// your logic
}).catch(error => {
console.error("Silent Error: " + error);
if (error instanceof msal.InteractionRequiredAuthError) {
myMSALObj.loginRedirect(loginRequest);
}
});
You can pass custom query string parameters to your sign-in request, using the extraQueryParameters
property. For instance, in order to customize your B2C user interface, you can:
const loginRequest = {
scopes: ["openid", "profile"],
extraQueryParameters: { campaignId: 'hawaii', ui_locales: 'es' }
};
myMSALObj.loginRedirect(loginRequest);
See here for more: Customize the user interface of your application in Azure AD B2C
You can get all the active accounts of a signed-in user with the get getAllAccounts()
API. If you know the home ID of an account, you can select it by:
myMSALObj.getAccountByHomeId(homeId);
⚠️ MSAL.js also provides agetAccountByUsername()
API, which is not recommended with B2C as the B2C server may not return a username and as such, home ID is a more robust identifier to select an account.
The application redirects the user to the Microsoft identity platform logout endpoint to sign out. This endpoint clears the user's session from the browser. If your app did not go to the logout endpoint, the user may re-authenticate to your app without entering their credentials again, because they would have a valid single sign-in session with the Microsoft identity platform endpoint. See for more: Send a sign-out request.
The sign-out clears the user's single sign-on session with Azure AD B2C, but it might not sign the user out of their social identity provider session. If the user selects the same identity provider during a subsequent sign-in, they might re-authenticate without entering their credentials. Here the assumption is that, if a user wants to sign out of the application, it doesn't necessarily mean they want to sign out of their social account (e.g. Facebook) itself.
A single-page application does not benefit from validating ID tokens, since the application runs without a back-end and as such, attackers can intercept and edit the keys used for validation of the token.
- Sign-up/sign-in
This user-flow allows your users to sign-in to your application if the user has an account already, or sign-up for an account if not. This is the default user-flow that we pass during the initialization of MSAL instance.
- Password reset
When a user clicks on the forgot your password? link during sign-in, Azure AD B2C will throw an error. To initiate the password reset user-flow, you need to catch this error and handle it by sending another login request with the corresponding password reset authority string.
myMSALObj.loginPopup(loginRequest)
.then(handleResponse)
.catch(error => {
console.error(error);
if (error.errorMessage) {
if (error.errorMessage.indexOf("AADB2C90118") > -1) {
myMSALObj.loginPopup(b2cPolicies.authorities.forgotPassword)
.then(response => {
console.log(response);
window.alert("Password has been reset successfully. \nPlease sign-in with your new password.");
})
}
}
});
In case if you are using redirect flow, you should catch the error inside handleRedirectPromise()
:
myMSALObj.handleRedirectPromise()
.then(handleResponse)
.catch(error => {
console.error(error);
if (error.errorMessage.indexOf("AADB2C90118") > -1) {
try {
myMSALObj.loginRedirect(b2cPolicies.authorities.forgotPassword);
} catch(err) {
console.log(err);
}
}
});
Then, in handleResponse()
:
function handleResponse(response) {
if (response !== null) {
if (response.idTokenClaims['acr'] === b2cPolicies.names.forgotPassword) {
window.alert("Password has been reset successfully. \nPlease sign-in with your new password.");
const logoutRequest = {
account: myMSALObj.getAccountByHomeId(accountId),
postLogoutRedirectUri: "http://localhost:6420"
};
myMSALObj.logout(logoutRequest);
} else if (response.idTokenClaims['acr'] === b2cPolicies.names.editProfile) {
window.alert("Profile has been updated successfully.");
} else {
// sign-in as usual
}
}
}
- Edit Profile
Unlike password reset, edit profile user-flow does not require users to sign-out and sign-in again. Instead, MSAL.js will handle switching back to the authority string of the default user-flow automatically.
myMSALObj.loginPopup(b2cPolicies.authorities.editProfile)
.then(response => {
console.log(response);
// your logic here
});
Continue with the next tutorial: Protect and call a web API.
Configure your application:
- Use Microsoft Authentication Library for JavaScript to work with Azure AD B2C
- Tutorial: Create an Azure Active Directory B2C tenant
- Single sign-on with MSAL.js
- Handle MSAL.js exceptions and errors
- Logging in MSAL.js applications
Learn more about Microsoft identity platform and Azure AD B2C:
- Microsoft identity platform (Azure Active Directory for developers)
- Overview of Microsoft Authentication Library (MSAL)
- What is Azure Active Directory B2C?
- Azure AD B2C User Flows
- Azure AD B2C Custom Policies
For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.
Use Stack Overflow to get support from the community.
Ask your questions on Stack Overflow first and browse existing issues to see if someone has asked your question before.
Make sure that your questions or comments are tagged with [azure-ad
azure-ad-b2c
ms-identity
msal
].
If you find a bug in the sample, please raise the issue on GitHub Issues.
To provide a recommendation, visit the following User Voice page.