Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This tutorial teaches you how to build a JavaScript console app that uses the Microsoft Graph API to access data using app-only authentication. App-only authentication is a good choice for background services or applications that need to access data for all users in an organization.
Note
To learn how to use Microsoft Graph to access data on behalf of a user, see this user (delegated) authentication tutorial.
In this tutorial, you will:
Tip
As an alternative to following this tutorial, you can download or clone the GitHub repository and follow the instructions in the README to register an application and configure the project.
Prerequisites
Before you start this tutorial, you should have Node.js installed on your development machine.
You should also have a Microsoft work or school account with the Global administrator role. If you don't have a Microsoft 365 tenant, you might qualify for one through the Microsoft 365 Developer Program; for details, see the FAQ. Alternatively, you can sign up for a one-month free trial or purchase a Microsoft 365 plan.
Note
This tutorial was written with Node.js version 16.14.2. The steps in this guide might work with other versions, but that hasn't been tested.
Register application for app-only authentication
Register an application that supports app-only authentication using client credentials flow.
Open a browser and navigate to the Microsoft Entra admin center and sign in using a Global administrator account.
Select Microsoft Entra ID in the left-hand navigation, expand Identity, expand Applications, then select App registrations.
Select New registration. Enter a name for your application, for example,
Graph App-Only Auth Tutorial
.Set Supported account types to Accounts in this organizational directory only.
Leave Redirect URI empty.
Select Register. On the application's Overview page, copy the value of the Application (client) ID and Directory (tenant) ID and save them. You'll need these values in the next step.
Select API permissions under Manage.
Remove the default User.Read permission under Configured permissions by selecting the ellipses (...) in its row and selecting Remove permission.
Select Add a permission, then Microsoft Graph.
Select Application permissions.
Select User.Read.All, then select Add permissions.
Select Grant admin consent for..., then select Yes to provide admin consent for the selected permission.
Select Certificates and secrets under Manage, then select New client secret.
Enter a description, choose a duration, and select Add.
Copy the secret from the Value column, you'll need it in the next steps.
Important
This client secret is never shown again, so make sure you copy it now.
Note
Notice that, unlike the steps when registering for user authentication, in this section you did configure Microsoft Graph permissions on the app registration. App-only auth uses the client credentials flow, which requires that permissions be configured on the app registration. See The .default scope for details.
Create a JavaScript console app
Begin by creating a new Node.js project. Open your command-line interface (CLI) in a directory where you want to create the project. Run the following command.
npm init
Answer the prompts by either supplying your own values or accepting the defaults.
Install dependencies
Before moving on, add dependencies that you use later.
- Azure Identity client library for JavaScript to authenticate the user and acquire access tokens.
- Microsoft Graph JavaScript client library to make calls to the Microsoft Graph.
- isomorphic-fetch to add
fetch
API to Node.js. This is a dependency for the Microsoft Graph JavaScript client library. - readline-sync for prompting the user for input.
To install the dependencies, run the following commands in your CLI.
npm install @azure/identity @microsoft/microsoft-graph-client isomorphic-fetch readline-sync
Load application settings
Add the details of your app registration to the project.
Create a file in the root of your project named appSettings.js and add the following code.
const settings = { clientId: 'YOUR_CLIENT_ID_HERE', clientSecret: 'YOUR_CLIENT_SECRET_HERE', tenantId: 'YOUR_TENANT_ID_HERE', }; export default settings;
Update the values in
settings
according to the following table.Setting Value clientId
The client ID of your app registration tenantId
The tenant ID of your organization. clientSecret
The client secret generated in the previous step
Design the app
Create a console-based menu.
Create a file in the root of your project named graphHelper.js and add the following placeholder code. You add more code this file in later steps.
module.exports = {};
Create a file in the root of your project named index.js and add the following code.
import { keyInSelect } from 'readline-sync'; import settings from './appSettings.js'; import { initializeGraphForAppOnlyAuth, getAppOnlyTokenAsync, getUsersAsync, makeGraphCallAsync, } from './graphHelper.js'; async function main() { console.log('JavaScript Graph App-Only Tutorial'); let choice = 0; // Initialize Graph initializeGraph(settings); const choices = ['Display access token', 'List users', 'Make a Graph call']; while (choice != -1) { choice = keyInSelect(choices, 'Select an option', { cancel: 'Exit' }); switch (choice) { case -1: // Exit console.log('Goodbye...'); break; case 0: // Display access token await displayAccessTokenAsync(); break; case 1: // List emails from user's inbox await listUsersAsync(); break; case 2: // Run any Graph code await doGraphCallAsync(); break; default: console.log('Invalid choice! Please try again.'); } } } main();
Add the following placeholder methods at the end of the file. You implement them in later steps.
function initializeGraph(settings) { // TODO } async function displayAccessTokenAsync() { // TODO } async function listUsersAsync() { // TODO } async function doGraphCallAsync() { // TODO }
This implements a basic menu and reads the user's choice from the command line.