Skip to content

Files

Latest commit

3cd6ef5 · Apr 14, 2025

History

History

vanillajs-spa

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Apr 14, 2025
Mar 5, 2024
Mar 3, 2025
page_type languages products name url-fragment description
sample
javascript
azure
azure-active-directory
ms-graph
microsoft-identity-platform
JavaScript single-page app (SPA) that signs in user
msal-javascript-single-page-app
This minimal JavaScript application demonstrates usage of the Microsoft Authentication Library for JavaScript (MSAL.js) to sign in Microsoft Entra users (authentication), call a protected web API (authorization), and sign out users.

Vanilla JavaScript single-page application using MSAL.js to authenticate users with Microsoft Entra ID

Overview

This sample demonstrates how to sign users into a sample Vanilla JavaScript single-page application (SPA) tby using Microsoft Entra ID. The sample utilizes the Microsoft Authentication Library for JavaScript (MSAL.js) to simplify adding authentication.

Usage

Instruction Description
Use case Authenticate users and call a protected web API.
Scenario Sign in users. You acquire an ID token by using authorization code flow with PKCE.
Add sign in to your app Use the instructions in Sign in users in a single-page app (SPA) and call the Microsoft Graph API using JavaScript to learn how to add sign in to your JavaScript SPA.
Product documentation Explore Microsoft Entra ID for customers documentation

Contents

File/folder Description
public/authConfig.js Contains configuration parameters for the sample.
public/auth.js Used for authentication with redirect flow.
public/ui.js Contains UI logic.
server.js Node server for index.html.

Prerequisites

This sample will not work with a personal Microsoft account. If you're signed in to the Microsoft Entra admin center with a personal Microsoft account and have not created a user account in your directory before, you will need to create one before proceeding.

Clone or download the sample application

To obtain the sample application, you can either clone it from GitHub or download it as a .zip file.

  • To clone the sample, open a command prompt and navigate to where you wish to create the project, and enter the following command:

    git clone https://github.com/Azure-Samples/ms-identity-docs-code-javascript
  • Download the .zip file. Extract it to a file path where the length of the name is fewer than 260 characters.

Register the SPA in your tenant

You can register an app in your tenant automatically by using Microsoft Graph PowerShell or via the Microsoft Entra Admin center.

When you use Microsoft Graph PowerShell, you automatically register the applications and related objects app secrets, then modify your project config files, so you can run the app without any further action:

  • To register your app in the Microsoft Entra admin center use the steps in Register the web app.

  • To register and configure your app automatically,

    Expand this section

    ⚠️ If you have never used Microsoft Graph PowerShell before, we recommend you go through the App Creation Scripts Guide once to ensure that you've prepared your environment correctly for this step.

    1. Ensure that you have PowerShell 7 or later installed.

    2. Run the script to create your Microsoft Entra ID application and configure the code of the sample application accordingly.

    3. For interactive process in PowerShell, run:

      cd .\AppCreationScripts\
      .\Configure.ps1 -TenantId "[Optional] - your tenant id" -AzureEnvironmentName "[Optional] - Azure environment, defaults to 'Global'"

    Other ways of running the scripts are described in App Creation Scripts guide. The scripts also provides a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.

    ❗ NOTE: This sample can make use of client certificates. You can use AppCreationScripts to register an Microsoft Entra ID application with certificates. For more information see, Use client certificate for authentication in your Node.js web app instead of client secrets.

Configure the project

  1. Open the project folder, ms-identity-javascript-tutorial, containing the sample.

  2. Open 1-Authentication/1-sign-in/App/authConfig.js and update the following values with the information recorded earlier in the admin center.

    • clientId - The identifier of the application, also referred to as the client. Replace the text in quotes with the Application (client) ID value that was recorded earlier.
    • authority - The authority is a URL that indicates a directory that MSAL can request tokens from. Replace Enter_the_Tenant_Info_Here with the Directory (tenant) ID value that was recorded earlier.
    • redirectUri - The Redirect URI of the application. If necessary, replace the text in quotes with the redirect URI that was recorded earlier.

Run the application and sign in

Run the project with a web server by using Node.js:

  1. To start the server, run the following commands from within the project directory:

    npm install
    npm start

Explore the sample

  1. Open your browser and navigate to http://localhost:3000.
  2. Click the sign-in button on the top right corner.

Screenshot

ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.

We'd love your feedback

Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.

Troubleshooting

Expand for troubleshooting info

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-active-directory ms-identity adal msal].

About the code

Sign-in

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 provideshandleRedirectPromise() 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: "example@domain.net"
    };

    myMSALObj.ssoSilent(silentRequest)
        .then((response) => {
            // your logic
        }).catch(error => {
            console.error("Silent Error: " + error);
            if (error instanceof msal.InteractionRequiredAuthError) {
                myMSALObj.loginRedirect(loginRequest);
            }
        });

You can get all the active accounts of a user with the get getAllAccounts() API. If you know the username or home ID of an account, you can select it by:

    myMSALObj.getAccountByUsername(username);
    // or
    myMSALObj.getAccountByHomeId(homeId);

Sign-out

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. For more, see: Send a sign-out request

ID Token Validation

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-in Audience and Account Types

This sample is meant to work with accounts in your organization (aka single-tenant). If you would like to allow sign-ins with other type accounts, you have to configure your authority string in authConfig.js accordingly. For example:

const msalConfig = {
    auth: {
      clientId: 'Enter_the_Application_Id_Here', // This is the ONLY mandatory field that you need to supply.
      authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here', 
      redirectUri: 'Enter_the_Redirect_URI_Here/',
    },

For more information about audiences and account types, please see: Validation differences by supported account types (signInAudience)

⚠️ Be aware that making an application multi-tenant entails more than just modifying the authority string. For more information, please see How to: Sign in any Microsoft Entra user using the multi-tenant application pattern.

Authentication in National Clouds

National clouds (aka Sovereign clouds) are physically isolated instances of Azure. These regions of Azure are designed to make sure that data residency, sovereignty, and compliance requirements are honored within geographical boundaries. Enabling your application for sovereign clouds requires you to:

  • register your application in a specific portal, depending on the cloud.
  • use a specific authority, depending on the cloud in the configuration file for your application.
  • in case you want to call the MS Graph, this requires a specific Graph endpoint URL, depending on the cloud.

See National Clouds for more information.

Contributing

If you'd like to contribute to this sample, see CONTRIBUTING.MD.

This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.

Learn More