Skip to content

Latest commit

 

History

History
 
 

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

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
  11. Community Help and Support
  12. Contributing
  13. Code of Conduct

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
AppCreationScripts/ Contains Powershell scripts to automate app registration.
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.
SPA/server.js Simple Node server for index.html.
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/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.

Step 2: Install project dependencies

    cd ms-identity-javascript-tutorial
    cd 3-Authorization-II/1-call-api
    cd API
    npm install
    cd..
    cd SPA
    npm install

Registration

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

There is one project in this sample. To register it, you can:

  • either follow the steps below for manually register your apps
  • or use PowerShell scripts that:
    • automatically creates the Azure AD applications and related objects (passwords, permissions, dependencies) for you.
    • modify the projects' configuration files.
Expand this section if you want to use this automation:

⚠️ If you have never used Azure AD Powershell before, we recommend you go through the App Creation Scripts once to ensure that your environment is prepared correctly for this step.

  1. On Windows, run PowerShell and navigate to the root of the cloned directory.

  2. In PowerShell run:

    Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
  3. Run the script to create your Azure AD application and configure the code of the sample application accordingly.

  4. In PowerShell run:

    cd .\AppCreationScripts\
    .\Configure.ps1

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

Follow the steps below to manually walk through the steps to register and configure the applications in the Azure portal.

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 (msal-node-api)

  1. Navigate to the Azure portal and select the Azure Active Directory 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:
    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example msal-node-api.
    2. Under Supported account types, select Accounts in this organizational directory only
    3. Select Register to create the application.
  4. In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
  5. In the app's registration screen, select the Authentication blade to the left.
  6. If you don't have a platform added, select Add a platform and select the Web option.
    1. In the Redirect URI section enter the following redirect URI:
      1. ``
    2. Click 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 publish the permission 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(Application ID URI), follow the following steps:
    1. Select Set next to the Application ID URI to generate a URI that is unique for this app.
    2. For this sample, accept the proposed Application ID URI (api://{clientId}) by selecting Save.

      ℹ️ Read more about Application ID URI at Validation differences by supported account types (signInAudience).

Publish Delegated Permissions

  1. All APIs must publish a minimum of one scope, also called Delegated Permission, for the client apps to obtain an access token for a user successfully. To publish a scope, follow these steps:
  2. Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
    1. For Scope name, use Todolist.Read.
    2. Select Admins and users options for Who can consent?.
    3. For Admin consent display name type in Todolist.Read.
    4. For Admin consent description type in e.g. Allows the app to read the signed-in user's files..
    5. For User consent display name type in scopeName.
    6. For User consent description type in eg. Allows the app to read your files..
    7. Keep State as Enabled.
    8. Select the Add scope button on the bottom to save this scope.

    Repeat the steps above for another scope named Todolist.ReadWrite

  3. Select the Manifest blade on the left.
    1. Set accessTokenAcceptedVersion property to 2.
    2. Select on Save.

ℹ️ Follow the principle of least privilege when publishing permissions for a web API.

Publish Application Permissions

  1. All APIs should publish a minimum of one App role for applications, also called Application Permission, for the client apps to obtain an access token as themselves, i.e. when they are not signing-in a user. Application permissions are the type of permissions that APIs should publish when they want to enable client applications to successfully authenticate as themselves and not need to sign-in users. To publish an application permission, follow these steps:
  2. Still on the same app registration, select the App roles blade to the left.
  3. Select Create app role:
    1. For Display name, enter a suitable name for your application permission, for instance Todolist.Read.All.
    2. For Allowed member types, choose Application to ensure other applications can be granted this permission.
    3. For Value, enter Todolist.Read.All.
    4. For Description, enter e.g. Allows the app to read the signed-in user's files..
    5. Select Apply to save your changes.

    Repeat the steps above for another app permission named Todolist.ReadWrite.All

Configure Optional Claims

  1. Still on the same app registration, select the Token configuration blade to the left.
  2. Select Add optional claim:
    1. Select optional claim type, then choose Access.
    2. Select the optional claim idtyp.

    Indicates token type. This claim is the most accurate way for an API to determine if a token is an app token or an app+user token. This is not issued in tokens issued to users.

    1. Select the optional claim acct.

    Provides user's account status in tenant. If the user is a member of the tenant, the value is 0. If they're a guest, the value is 1.

    1. Select Add to save your changes.

Configure the service app (msal-node-api) 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 API\authConfig.js file.
  2. Find the key Enter_the_Application_Id_Here and replace the existing value with the application ID (clientId) of msal-node-api app copied from the Azure portal.
  3. Find the key Enter_the_Tenant_Info_Here and replace the existing value with your Azure AD tenant/directory ID.

Register the client app (msal-javascript-spa)

  1. Navigate to the Azure portal and select the Azure Active Directory 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:
    1. In the Name section, enter a meaningful application name that will be displayed to users of the app, for example msal-javascript-spa.
    2. Under Supported account types, select Accounts in this organizational directory only
    3. Select Register to create the application.
  4. In the Overview blade, find and note the Application (client) ID. You use this value in your app's configuration file(s) later in your code.
  5. In the app's registration screen, select the Authentication blade to the left.
  6. If you don't have a platform added, select Add a platform and select the Single-page application option.
    1. In the Redirect URI section enter the following redirect URIs:
      1. http://localhost:3000
      2. http://localhost:3000/redirect
    2. Click Save to save your changes.
  7. Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
    1. In the app's registration screen, select the API permissions blade in the left to open the page where we add access to the APIs that your application needs:
    2. Select the Add a permission button and then:
    3. Ensure that the My APIs tab is selected.
    4. In the list of APIs, select the API msal-node-api.
    5. In the Delegated permissions section, select Todolist.Read, Todolist.ReadWrite in the list. Use the search box if necessary.
    6. Select the Add permissions button at the bottom.

Configure Optional Claims

  1. Still on the same app registration, select the Token configuration blade to the left.
  2. Select Add optional claim:
    1. Select the optional claim acct.

    Provides user's account status in tenant. If the user is a member of the tenant, the value is 0. If they're a guest, the value is 1.

    1. Select Add to save your changes.

Configure the client app (msal-javascript-spa) 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 SPA\public\authConfig.js file.
  2. Find the key Enter_the_Application_Id_Here and replace the existing value with the application ID (clientId) of msal-javascript-spa app copied from the Azure portal.
  3. Find the key Enter_the_Tenant_Info_Here and replace the existing value with your Azure AD tenant/directory ID.
  4. Find the key Enter_the_Web_Api_Application_Id_Here and replace the existing value with the application ID (clientId) of msal-node-api app copied from the Azure portal.

Running the sample

    cd ms-identity-javascript-tutorial
    cd 3-Authorization-II/1-call-api
    cd API
    npm start
    cd ..
    cd SPA
    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.
  3. Once you authenticate, click the Call API button at the center.

Screenshot

We'd love your feedback!

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

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.

CORS settings

For the purpose of the sample, cross-origin resource sharing (CORS) is enabled for all domains and methods, using the Express.js cors middleware. This is insecure and only used for demonstration purposes here. In production, you should modify this as to allow only the domains that you designate. If your web API is going to be hosted on Azure App Service, we recommend configuring CORS on the App Service itself. This is illustrated in app.js:

const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

Access token validation

On the web API side, passport-azure-ad verifies the incoming access token's signature and validates it's payload against the issuer and audience claims (defined in BearerStrategy constructor) using the passport.authenticate() API. In the BearerStrategy callback, you can add further validation steps as shown below (see app.js):

const express = require('express');
const passport = require('passport');
const passportAzureAd = require('passport-azure-ad');

const app = express();

const bearerStrategy = new passportAzureAd.BearerStrategy({
    identityMetadata: `https://${authConfig.metadata.authority}/${authConfig.credentials.tenantID}/${authConfig.metadata.version}/${authConfig.metadata.discovery}`,
    issuer: `https://${authConfig.metadata.authority}/${authConfig.credentials.tenantID}/${authConfig.metadata.version}`,
    clientID: authConfig.credentials.clientID,
    audience: authConfig.credentials.clientID, // audience is this application
    validateIssuer: authConfig.settings.validateIssuer,
    passReqToCallback: authConfig.settings.passReqToCallback,
    loggingLevel: authConfig.settings.loggingLevel,
    loggingNoPII: authConfig.settings.loggingNoPII,
}, (req, token, done) => {
    /**
     * Access tokens that have neither the 'scp' (for delegated permissions) nor
     * 'roles' (for application permissions) claim are not to be honored.
     */
    if (!token.hasOwnProperty('scp') && !token.hasOwnProperty('roles')) {
        return done(new Error('Unauthorized'), null, "No delegated or app permission claims found");
    }

    /**
     * If needed, pass down additional user info to route using the second argument below.
     * This information will be available in the req.user object.
     */
    return done(null, {}, token);
});

app.use(passport.initialize());

passport.use(bearerStrategy);

// exposed API endpoint
app.use('/api',
    passport.authenticate('oauth-bearer', {
        session: false,
    }),
    router
);

For validation and debugging purposes, developers can decode JWTs (JSON Web Tokens) using jwt.ms.

Verifying permission type

Web API endpoints should be prepared to accept calls from both users and applications, and should have control structures in place to respond each accordingly. This is illustrated in permissionUtils.js:

const isAppOnlyToken = (accessTokenPayload) => {

     if (!accessTokenPayload.hasOwnProperty('idtyp')) {
        if (accessTokenPayload.hasOwnProperty('scp')) {
            return false;
        } else if (!accessTokenPayload.hasOwnProperty('scp') && accessTokenPayload.hasOwnProperty('roles')) {
            return true;
        }
    }

    return accessTokenPayload.idtyp === 'app';
};

Access to data

Controllers should check if the presented access token has the necessary permissions to access the data, depending on the type of permission. This is illustrated in todolist.js:

exports.getTodos = (req, res, next) => {
    if (isAppOnlyToken(req.authInfo)) {
        if (hasRequiredApplicationPermissions(req.authInfo, authConfig.protectedRoutes.todolist.applicationPermissions.read)) {
            try {
                const todos = db.get('todos')
                    .value();
    
                res.status(200).send(todos);
            } catch (error) {
                next(error);
            }
        } else {
            next(new Error('Application does not have the required permissions'))
        }
    } else {
        if (hasRequiredDelegatedPermissions(req.authInfo, authConfig.protectedRoutes.todolist.delegatedPermissions.read)) {
            try {
                const owner = req.authInfo['oid'];
    
                const todos = db.get('todos')
                    .filter({ owner: owner })
                    .value();
    
                res.status(200).send(todos);
            } catch (error) {
                next(error);
            }
        } else {
            next(new Error('User does not have the required permissions'))
        }
    }
}

When granting access to data based on scopes, be sure to follow the principle of least privilege.

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.

Community Help and Support

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.

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 [email protected] with any additional questions or comments.

Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.