page_type | name | description | languages | products | urlFragment | extensions | ||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
sample |
Vanilla JavaScript single-page application using MSAL.js to authenticate users to call Microsoft Graph |
Vanilla JavaScript single-page application using MSAL.js to authenticate users and calling the Microsoft Graph API on their behalf |
|
|
ms-identity-javascript-tutorial |
|
Vanilla JavaScript single-page application using MSAL.js to authenticate users to call Microsoft Graph
- Overview
- Scenario
- Contents
- Prerequisites
- Setup the sample
- Explore the sample
- Troubleshooting
- About the code
- Next Steps
- Contributing
- Learn More
This sample demonstrates a Vanilla JavaScript single-page application that lets users authenticate against Microsoft Entra ID (Microsoft Entra ID) using the Microsoft Authentication Library for JavaScript (MSAL.js), then acquires an Access Token for Microsoft Graph and calls the Microsoft Graph API. In doing so, it also illustrates various authorization concepts, such as Access Tokens, Authorization Code Grant, Dynamic Scopes and Incremental Consent, silent requests and more.
In addition, this sample also demonstrates how to use the Microsoft Graph JavaScript SDK client with MSAL as a custom authentication provider to query the Graph API. Note that you are not required to implement a custom provider, as the v3.0 (preview) of the SDK offers a default provider that implements MSAL.js.
ℹ️ To learn how applications integrate with Microsoft Graph, consider going through the recorded session:: An introduction to Microsoft Graph for developers
- The client application uses the MSAL.js to sign-in a user and obtain a JWT Access Token from Microsoft Entra ID:
- The Access Token is used as a bearer token to authorize the user to call the Microsoft Graph API.
- Microsoft Graph API responds with the resource that the user has access to.
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. |
App/graph.js |
Implements custom authentication provider for Graph SDK. |
App/ui.js |
Contains UI logic. |
server.js |
Simple Express server for index.html . |
- Node.js must be installed to run this sample.
- 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.
- A modern web browser.
- An Microsoft Entra ID tenant. For more information, see: How to get a Microsoft Entra tenant
- A user account in your Microsoft Entra ID tenant.
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.
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 2-Authorization-I\1-call-graph
npm install
There is one project in this sample. To register it, you can:
- follow the steps below for manually register your apps
- or use PowerShell scripts that:
- automatically creates the Microsoft Entra applications and related objects (passwords, permissions, dependencies) for you.
- modify the projects' configuration files.
Expand this section if you want to use this automation:
> :warning: If you have never used **Microsoft Graph PowerShell** before, we recommend you go through the [App Creation Scripts Guide](./AppCreationScripts/AppCreationScripts.md) once to ensure that your environment is prepared correctly for this step.
1. On Windows, run PowerShell as **Administrator** and navigate to the root of the cloned directory
1. In PowerShell run:
```PowerShell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process -Force
```
1. Run the script to create your Microsoft Entra application and configure the code of the sample application accordingly.
1. For interactive process -in PowerShell, run:
```PowerShell
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](./AppCreationScripts/AppCreationScripts.md). The scripts also provide a guide to automated application registration, configuration and removal which can help in your CI/CD scenarios.
To manually register the apps, as a first step you'll need to:
- Sign in to the Microsoft Entra admin center.
- If your account is present in more than one Microsoft Entra 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 Microsoft Entra tenant.
- Navigate to the Microsoft Entra admin center and select the Microsoft Entra ID 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
ms-identity-javascript-c2s1
. - 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 Microsoft APIs tab is selected.
- In the Commonly used Microsoft APIs section, select Microsoft Graph
- In the Delegated permissions section, select User.Read, Contacts.Read 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 optional claim type, then choose ID.
- 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 the optional claim login_hint.
An opaque, reliable login hint claim. This claim is the best value to use for the login_hint OAuth parameter in all flows to get SSO.See $optional claims for more details on this optional claim.
- 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
App\authConfig.js
file. - Find the key
Enter_the_Application_Id_Here
and replace the existing value with the application ID (clientId) ofms-identity-javascript-c2s1
app copied from the Microsoft Entra admin center. - Find the key
Enter_the_Tenant_Id_Here
and replace the existing value with your Microsoft Entra tenant/directory ID.
cd 2-Authorization-I\1-call-graph
npm start
- Open your browser and navigate to
http://localhost:3000
. - Click the sign-in button on the top right corner.
- Next, click the See my profile button on the left. This will make a MS Graph call.
- Click the Read my contacts button below to see your contacts.
ℹ️ Did the sample not work for you as expected? Then please reach out to us using the GitHub Issues page.
Were we successful in addressing your learning objective? Consider taking a moment toshare your experience with us.
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
msal-js
ms-identity
adal
msal
].
To provide feedback on or suggest features for Microsoft Entra ID, visit User Voice page.
In order to access a protected resource on behalf of a signed-in user, the app needs to present a valid Access Token to that resource owner (in this case, Microsoft Graph). The intended recipient of an Access Token is represented by the aud
claim (in this case, it should be the Microsoft Graph API's App ID); 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.
In Microsoft Entra ID, 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: [ "Contacts.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.
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.
myMSALObj.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);
});
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. This sample does not need to validate Access Tokens it acquires.
Microsoft Graph JavaScript SDK provides various utility methods to query the Graph API. While the SDK has a default authentication provider that can be used in basic scenarios, it can also be extended to use with a custom authentication provider such as MSAL. To do so, we will initialize the Graph SDK client with clientOptions method, which contains an authProvider
object of class MyAuthenticationProvider that handles the token acquisition process for the client.
const getGraphClient = () => {
let clientOptions = {
authProvider: new MyAuthenticationProvider(),
};
const graphClient = Client.initWithMiddleware(clientOptions);
return graphClient;
}
MyAuthenticationProvider needs to implement the IAuthenticationProvider interface, which can be done as shown below:
class MyAuthenticationProvider {
/**
* This method will get called before every request to the ms graph server
* This should return a Promise that resolves to an accessToken (in case of success) or rejects with error (in case of failure)
* Basically this method will contain the implementation for getting and refreshing accessTokens
*/
getAccessToken() {
return new Promise(async (resolve, reject) => {
let response;
response = await msalInstance.acquireTokenSilent({
account: account,
scopes: scopes
});
if (response.accessToken) {
resolve(response.accessToken);
} else {
reject(Error('Failed to acquire an access token'));
}
});
}
}
See graph.js. The Graph client then can be used as shown below:
function readContacts() {
const account = myMSALObj.getAccountByUsername(username);
getGraphClient({
account: account,
scopes: graphConfig.graphContactsEndpoint.scopes,
interactionType: msal.InteractionType.Popup,
})
.api('/me/contacts')
.responseType('raw')
.get()
.then((response) => {
return handleClaimsChallenge(account, response, graphConfig.graphContactsEndpoint.uri);
})
.then((response) => {
if (response && response.error === 'claims_challenge_occurred') throw response.error;
return updateUI(response, graphConfig.graphContactsEndpoint.uri);
})
.catch((error) => {
if (error === 'claims_challenge_occurred') {
const resource = new URL(graphConfig.graphContactsEndpoint.uri).hostname;
const claims =
account &&
getClaimsFromStorage(`cc.${msalConfig.auth.clientId}.${account.idTokenClaims.oid}.${resource}`)
? window.atob(
getClaimsFromStorage(
`cc.${msalConfig.auth.clientId}.${account.idTokenClaims.oid}.${resource}`
)
)
: undefined; // e.g {"access_token":{"xms_cc":{"values":["cp1"]}}}
let request = {
account: account,
scopes: graphConfig.graphContactsEndpoint.scopes,
claims: claims,
redirectUri: '/redirect',
};
myMSALObj.acquireTokenPopup(request).catch((error) => {
console.log(error);
});
} else if (error.toString().includes('404')) {
return updateUI(null, graphConfig.graphContactsEndpoint.uri);
} else {
console.log(error);
}
});
}
Continuous access evaluation (CAE) enables applications to do just-in time token validation, for instance enforcing user session revocation in the case of password change/reset but there are other benefits. For details, see Continuous access evaluation.
Microsoft Graph is now CAE-enabled in Preview. This means that it can ask its client apps for more claims when conditional access policies require it. Your can enable your application to be ready to consume CAE-enabled APIs by:
- Declaring that the client app is capable of handling claims challenges.
- Processing these challenges when they are thrown by the web API.
This sample app declares that it's CAE-capable by adding the clientCapabilities
property in the configuration in authConfig.js
:
const msalConfig = {
auth: {
clientId: 'Enter_the_Application_Id_Here',
authority: 'https://login.microsoftonline.com/Enter_the_Tenant_Info_Here',
redirectUri: "/",
postLogoutRedirectUri: "/",
navigateToLoginRequestUrl: true,
clientCapabilities: ["CP1"] // this lets the resource owner know that this client is capable of handling claims challenge.
}
}
const msalInstance = new PublicClientApplication(msalConfig);
Once the client app receives the CAE claims challenge from Microsoft Graph, it needs to present the user with a prompt for satisfying the challenge via Microsoft Entra authorization endpoint. To do so, we use MSAL's acquireTokenRedirect
and acquireTokenPopup
API's and provide the claims challenge as a parameter in the token request. This is shown in fetch.js, where we handle the response from the Microsoft Graph API with the handleClaimsChallenge
method:
/**
* This method inspects the HTTPS response from a fetch call for the "www-authenticate header"
* If present, it grabs the claims challenge from the header and store it in the localStorage
* For more information, visit: https://docs.microsoft.com/en-us/azure/active-directory/develop/claims-challenge#claims-challenge-header-format
* @param {object} response
* @returns response
*/
const handleClaimsChallenge = async (account,response, apiEndpoint) => {
if (response.status === 200) {
return response.json();
} else if (response.status === 401) {
if (response.headers.get('www-authenticate')) {
const authenticateHeader = response.headers.get('www-authenticate');
const claimsChallenge = parseChallenges(authenticateHeader);
/**
* This method stores the claim challenge to the session storage in the browser to be used when acquiring a token.
* To ensure that we are fetching the correct claim from the storage, we are using the clientId
* of the application and oid (user’s object id) as the key identifier of the claim with schema
* cc.<clientId>.<oid>.<resource.hostname>
*/
addClaimsToStorage(
claimsChallenge.claims,
`cc.${msalConfig.auth.clientId}.${account.idTokenClaims.oid}.${new URL(apiEndpoint).hostname}`
);
return { error: 'claims_challenge_occurred', payload: claimsChallenge.claims };
}
throw new Error(`Unauthorized: ${response.status}`);
} else {
throw new Error(`Something went wrong with the request: ${response.status}`);
}
};
After that, we require a new access token via the acquireTokenPopup
and acquireTokenRedirect
APIs, fetch the claims challenge from the browser's localStorage, and pass it to the acquireTokenPopup
and acquireTokenRedirect
APIs in the request parameter.
if (error === 'claims_challenge_occurred') {
const resource = new URL(graphConfig.graphMeEndpoint.uri).hostname;
const claims =
account &&
getClaimsFromStorage(`cc.${msalConfig.auth.clientId}.${account.idTokenClaims.oid}.${resource}`)
? window.atob(
getClaimsFromStorage(
`cc.${msalConfig.auth.clientId}.${account.idTokenClaims.oid}.${resource}`
)
)
: undefined; // e.g {"access_token":{"xms_cc":{"values":["cp1"]}}}
let request = {
account: account,
scopes: graphConfig.graphMeEndpoint.scopes,
claims: claims,
redirectUri: '/redirect',
};
myMSALObj.acquireTokenPopup(request).catch((error) => {
console.log(error);
});
}
Learn how to:
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.
- Microsoft identity platform (Microsoft Entra ID for developers)
- Microsoft Entra ID code samples
- Overview of Microsoft Authentication Library (MSAL)
- Register an application with the Microsoft identity platform
- Configure a client application to access web APIs
- Understanding Microsoft Entra application consent experiences
- Understand user and admin consent
- Application and service principal objects in Microsoft Entra ID
- Authentication Scenarios for Microsoft Entra ID
- Building Zero Trust ready apps
- National Clouds
- 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
- Use MSAL.js to work with Azure Active Directory B2C