Vanilla JavaScript single-page application (SPA) using MSAL.js to authorize users for calling a protected web API on Azure AD
- Overview
- Scenario
- Contents
- Prerequisites
- Setup
- Registration
- Running the sample
- Explore the sample
- About the code
- More information
- Community Help and Support
- Contributing
- Code of Conduct
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.
- The client application uses the MSAL.js library to sign-in a user and obtain a JWT Access Token from Azure AD.
- The Access Token is used as a bearer token to authorize the user to call the protected web API.
- The protected web API responds with the claims in the Access Token.
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. |
- 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.
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.
cd ms-identity-javascript-tutorial
cd 3-Authorization-II/1-call-api
cd API
npm install
cd..
cd SPA
npm install
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.
-
On Windows, run PowerShell and navigate to the root of the cloned directory.
-
In PowerShell run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
-
Run the script to create your Azure AD application and configure the code of the sample application accordingly.
-
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.
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 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..
- Navigate to the Azure portal and select the Azure Active Directory service.
- Select the App Registrations blade on the left, then 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
msal-node-api
. - Under Supported account types, select Accounts in this organizational directory only
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- 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.
- In the app's registration screen, select the Authentication blade to the left.
- If you don't have a platform added, select Add a platform and select the Web option.
- In the Redirect URI section enter the following redirect URI:
- ``
- Click Save to save your changes.
- In the Redirect URI section enter the following redirect URI:
- 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:
- Select 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.ℹ️ Read more about Application ID URI at Validation differences by supported account types (signInAudience).
- 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:
- Select Add a scope button open the Add a scope screen and Enter the values as indicated below:
- For Scope name, use
Todolist.Read
. - Select Admins and users options for Who can consent?.
- For Admin consent display name type in Todolist.Read.
- For Admin consent description type in e.g. Allows the app to read the signed-in user's files..
- For User consent display name type in scopeName.
- For User consent description type in eg. Allows the app to read your files..
- Keep State as Enabled.
- Select the Add scope button on the bottom to save this scope.
Repeat the steps above for another scope named Todolist.ReadWrite
- For Scope name, use
- Select the Manifest blade on the left.
- Set
accessTokenAcceptedVersion
property to 2. - Select on Save.
- Set
ℹ️ Follow the principle of least privilege when publishing permissions for a web API.
- 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:
- Still on the same app registration, select the App roles blade to the left.
- Select Create app role:
- For Display name, enter a suitable name for your application permission, for instance Todolist.Read.All.
- For Allowed member types, choose Application to ensure other applications can be granted this permission.
- For Value, enter Todolist.Read.All.
- For Description, enter e.g. Allows the app to read the signed-in user's files..
- Select Apply to save your changes.
Repeat the steps above for another app permission named Todolist.ReadWrite.All
- Still on the same app registration, select the Token configuration blade to the left.
- Select Add optional claim:
- Select optional claim type, then choose Access.
- 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.
- 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.
- Select Add to save your changes.
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
API\authConfig.js
file. - Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) ofmsal-node-api
app copied from the Azure portal. - Find the key
Enter_the_Tenant_Info_Here
and replace the existing value with your Azure AD tenant/directory ID.
- Navigate to the Azure portal and select the Azure Active Directory service.
- Select the App Registrations blade on the left, then 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
msal-javascript-spa
. - Under Supported account types, select Accounts in this organizational directory only
- Select Register to create the application.
- In the Name section, enter a meaningful application name that will be displayed to users of the app, for example
- 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.
- In the app's registration screen, select the Authentication blade to the left.
- If you don't have a platform added, select Add a platform and select the Single-page application option.
- In the Redirect URI section enter the following redirect URIs:
http://localhost:3000
http://localhost:3000/redirect
- Click Save to save your changes.
- In the Redirect URI section enter the following redirect URIs:
- Since this app signs-in users, we will now proceed to select delegated permissions, which is is required by apps signing-in users.
- 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:
- Select the Add a permission button and then:
- Ensure that the My APIs tab is selected.
- In the list of APIs, select the API
msal-node-api
. - In the Delegated permissions section, select Todolist.Read, Todolist.ReadWrite in the list. Use the search box if necessary.
- Select the Add permissions button at the bottom.
- Still on the same app registration, select the Token configuration blade to the left.
- Select Add optional claim:
- 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.
- Select Add to save your changes.
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
SPA\public\authConfig.js
file. - Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) ofmsal-javascript-spa
app copied from the Azure portal. - Find the key
Enter_the_Tenant_Info_Here
and replace the existing value with your Azure AD tenant/directory ID. - Find the key
Enter_the_Web_Api_Application_Id_Here
and replace the existing value with the application ID (clientId) ofmsal-node-api
app copied from the Azure portal.
cd ms-identity-javascript-tutorial
cd 3-Authorization-II/1-call-api
cd API
npm start
cd ..
cd SPA
npm start
- Open your browser and navigate to
http://localhost:3000
. - Click the sign-in button on the top right corner.
- Once you authenticate, click the Call API button at the center.
Were we successful in addressing your learning objective? Consider taking a moment to share your experience with us.
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);
});
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.
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());
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.
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';
};
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.
Configure your application:
- Initialize client applications using MSAL.js
- Single sign-on with MSAL.js
- Handle MSAL.js exceptions and errors
- Logging in MSAL.js applications
- Pass custom state in authentication requests using MSAL.js
- Prompt behavior in MSAL.js interactive requests
Learn more about Microsoft identity platform:
- Microsoft identity platform (Azure Active Directory for developers)
- Overview of Microsoft Authentication Library (MSAL)
- Understanding Azure AD application consent experiences
- Understand user and admin consent
- Microsoft identity platform and OpenID Connect protocol
- Microsoft identity platform ID Tokens
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.
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.
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.