Skip to content
This repository has been archived by the owner on Jun 4, 2023. It is now read-only.

Authentication with Microsoft identity platform in JavaScript.

License

Notifications You must be signed in to change notification settings

stever/ms-identity-example

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Vanilla JavaScript single-page application (SPA) using MSAL.js to authorize users for calling a protected web API on Azure AD

  1. Overview
  2. Scenario
  3. Contents
  4. Prerequisites
  5. Setup
  6. Registration
  7. Running the sample
  8. Explore the sample
  9. About the code
  10. More information

Overview

This sample demonstrates a Vanilla JavaScript single-page application (SPA) that lets users authenticate against Azure Active Directory (Azure AD) using the Microsoft Authentication Library for JavaScript (MSAL.js), then acquires an Access Token for a protected web API for the signed-in user and calls the protected web API. In doing so, it also illustrates various authorization concepts, such as token validation, CORS configuration, silent requests and more.

Scenario

  1. The client application uses the MSAL.js library to sign-in a user and obtain a JWT Access Token from Azure AD.
  2. The Access Token is used as a bearer token to authorize the user to call the protected web API.
  3. The protected web API responds with the claims in the Access Token.

Overview

Contents

File/folder Description
App/authRedirect.js Use this instead of authPopup.js for authentication with redirect flow.
App/authConfig.js Contains configuration parameters for the sample.
SPA/server.js Simple Node server for index.html.
API/process.json Contains configuration parameters for logging via Morgan.
API/index.js Main application logic resides here.
API/config.json Contains authentication parameters for the sample.

Prerequisites

  • Node.js must be installed to run this sample.
  • A modern web browser. This sample uses ES6 conventions and will not run on Internet Explorer.
  • Visual Studio Code is recommended for running and editing this sample.
  • VS Code Azure Tools extension is recommended for interacting with Azure through VS Code Interface.
  • An Azure AD tenant. For more information, see: How to get an Azure AD tenant
  • A user account in your Azure AD tenant.

Setup

Step 1: Clone or download this repository

From your shell or command line:

    git clone https://github.com/stever/ms-identity-example.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.

Step 2: Install project dependencies

    cd ms-identity-example
    git checkout example1
    npm install

Registration

Register the sample application(s) with your Azure Active Directory tenant

There are two projects in this sample. Each needs to be separately registered in your Azure AD tenant. To register these projects, you can follow the steps below for manually register your apps.

Choose the Azure AD tenant where you want to create your applications

As a first step you'll need to:

  1. Sign in to the Azure portal.
  2. If your account is present in more than one Azure AD 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 tenant..

Register the service app

  1. Navigate to the Azure portal and select the Azure AD service.
  2. Select the App Registrations blade on the left, then select New registration.
  3. 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-tutorial-c3s1-api.
    • Under Supported account types, select Accounts in this organizational directory only.
  4. Select Register to create the application.
  5. 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.
  6. Select Save to save your changes.
  7. In the app's registration screen, select the Expose an API blade to the left to open the page where you can declare the parameters to expose this app as an Api for which client applications can obtain access tokens for. The first thing that we need to do is to declare the unique resource URI that the clients will be using to obtain access tokens for this Api. To declare an resource URI, follow the following steps:
    • Click Set next to the Application ID URI to generate a URI that is unique for this app.
    • For this sample, accept the proposed Application ID URI (api://{clientId}) by selecting Save.
  8. All Apis have to publish a minimum of one scope for the client's to obtain an access token successfully. To publish a scope, follow the following steps:
    • Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
      • For Scope name, use access_as_user.
      • Select Admins and users options for Who can consent?
      • For Admin consent display name type ms-identity-javascript-c3s1-api
      • For Admin consent description type Allows the app to access ms-identity-javascript-tutorial-c3s1-api as the signed-in user.
      • For User consent display name type Access ms-identity-javascript-c3s1-api
      • For User consent description type Allow the application to access ms-identity-javascript-tutorial-c3s1-api on your behalf.
      • Keep State as Enabled
      • Click on the Add scope button on the bottom to save this scope.
  9. On the right side menu, select the Manifest blade.
    • Set accessTokenAcceptedVersion property to 2.
    • Click on Save.

Configure the service app to use your app registration

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".

  1. Open the config.json file.
  2. Find the key clientID and replace the existing value with the application ID (clientId) of the ms-identity-javascript-tutorial-c3s1-api application copied from the Azure portal.
  3. Find the key tenantID and replace the existing value with your Azure AD tenant ID.
  4. Find the key audience and replace the existing value with the application ID (clientId) of the ms-identity-javascript-tutorial-c3s1-api application copied from the Azure portal.

Register the client app

  1. Navigate to the Microsoft identity platform for developers App registrations page.
  2. Select New registration.
  3. 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-c3s1-spa.
    • Under Supported account types, select Accounts in your organizational directory only.
    • In the Redirect URI (optional) section, select Single-Page Application in the combo-box and enter the following redirect URI: http://localhost:3000/.
  4. Select Register to create the application.
  5. 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.
  6. Select Save to save your changes.
  7. In the app's registration screen, click on the API Permissions blade in the left to open the page where we add access to the APIs that your application needs.
    • Click the Add a permission button and then,
    • Ensure that the My APIs tab is selected.
    • In the list of APIs, select the API that you've just registered, i.e. ms-identity-javascript-tutorial-c3s1-api.
    • In the Delegated permissions section, select the access_as_user in the list. Use the search box if necessary.
    • Click on the Add permissions button at the bottom.

Configure the client app to use your app registration

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:

  1. Find the key Enter_the_Application_Id_Here and replace the existing value with the application ID (clientId) of the ms-identity-javascript-c3s1-spa application copied from the Azure portal.
  2. Find the key Enter_the_Tenant_Info_Here and replace the existing value with <your-tenant-id>.
  3. Find the key Enter_the_Redirect_Uri_Here and replace the existing value with the base address of the ms-identity-javascript-tutorial-c3s1-spa application (by default http://localhost:3000).
  4. Find the key Enter_the_Web_Api_Uri_Here and replace the existing value with the coordinates of your web API (by default http://localhost:5000/api).
  5. Find the key Enter_the_Web_Api_Scope_Here and replace the existing value with the scopes for your web API, like api://e767d418-b80b-4568-9754-557f40697fc5/access_as_user. You can copy this from the Expose an API blade of the web APIs registration.

Running the sample

    npm run dev

Explore the sample

  1. Open your browser and navigate to http://localhost:3000.
  2. Click the sign-in button on the top right corner.
  3. Once you authenticate, click the Call API button at the center.

Screenshot

About the code

Acquire a Token

Access Token requests in MSAL.js are meant to be per-resource-per-scope(s). This means that an Access Token requested for resource A with scope scp1:

  • cannot be used for accessing resource A with scope scp2, and,
  • cannot be used for accessing resource B of any scope.

The intended recipient of an Access Token is represented by the aud claim; in case the value for the aud claim does not mach the resource APP ID URI, the token should be considered invalid. Likewise, the permissions that an Access Token grants is represented by the scp claim. See Access Token claims for more information.

MSAL.js exposes 3 APIs for acquiring a token: acquireTokenPopup(), acquireTokenRedirect() and acquireTokenSilent():

    myMSALObj.acquireTokenPopup(request)
        .then(response => {
            // do something with response
        })
        .catch(error => {
            console.log(error)
        });

For acquireTokenRedirect(), you must register a redirect promise handler:

    myMSALObj.handleRedirectPromise()
        .then(response => {
            // do something with response
        })
        .catch(error => {
            console.log(error);
        });

    myMSALObj.acquireTokenRedirect(request);

The MSAL.js exposes the acquireTokenSilent() API which is meant to retrieve non-expired token silently.

    msalInstance.acquireTokenSilent(request)
        .then(tokenResponse => {
        // Do something with the tokenResponse
        }).catch(async (error) => {
            if (error instanceof InteractionRequiredAuthError) {
                // fallback to interaction when silent call fails
                return myMSALObj.acquireTokenPopup(request);
            }
        }).catch(error => {
            handleError(error);
        });

Dynamic Scopes and Incremental Consent

In Azure AD, the scopes (permissions) set directly on the application registration are called static scopes. Other scopes that are only defined within the code are called dynamic scopes. This has implications on the login (i.e. loginPopup, loginRedirect) and acquireToken (i.e. acquireTokenPopup, acquireTokenRedirect, acquireTokenSilent) methods of MSAL.js. Consider:

     const loginRequest = {
          scopes: [ "openid", "profile", "User.Read" ]
     };
     const tokenRequest = {
          scopes: [ "Mail.Read" ]
     };

     // will return an ID Token and an Access Token with scopes: "openid", "profile" and "User.Read"
     msalInstance.loginPopup(loginRequest);

     // will fail and fallback to an interactive method prompting a consent screen
     // after consent, the received token will be issued for "openid", "profile" ,"User.Read" and "Mail.Read" combined
     msalInstance.acquireTokenSilent(tokenRequest);

In the code snippet above, the user will be prompted for consent once they authenticate and receive an ID Token and an Access Token with scope User.Read. Later, if they request an Access Token for User.Read, they will not be asked for consent again (in other words, they can acquire a token silently). On the other hand, the user did not consented to Mail.Read at the authentication stage. As such, they will be asked for consent when requesting an Access Token for that scope. The token received will contain all the previously consented scopes, hence the term incremental consent.

Token Validation

On the web API side, passport-azure-ad validates the token against the issuer, scope and audience claims (defined in BearerStrategy constructor) using the passport.authenticate() API:

    app.get('/api', passport.authenticate('oauth-bearer', { session: false }),
        (req, res) => {
            console.log('Validated claims: ', req.authInfo)
        }
    );

Clients should treat access tokens as opaque strings, as the contents of the token are intended for the resource only (such as a web API or Microsoft Graph). For validation and debugging purposes, developers can decode JWTs (JSON Web Tokens) using a site like jwt.ms.

CORS Settings

For the purpose of the sample, cross-origin resource sharing is enabled for all domains. This is insecure. In production, you should modify this as to allow only the domains that you designate.

    app.use((req, res, next) => {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
        next();
    });

More information

Configure your application:

Learn more about Microsoft identity platform:

For more information about how OAuth 2.0 protocols work in this scenario and other scenarios, see Authentication Scenarios for Azure AD.

About

Authentication with Microsoft identity platform in JavaScript.

Topics

Resources

License

Stars

Watchers

Forks

Languages

  • JavaScript 79.0%
  • HTML 21.0%