Tutorial: Access Microsoft Graph from a secured JavaScript app as the app

Learn how to access Microsoft Graph from a web app running on Azure App Service.

Diagram that shows accessing Microsoft Graph.

You want to call Microsoft Graph for the web app. A safe way to give your web app access to data is to use a system-assigned managed identity. A managed identity from Azure Active Directory allows App Service to access resources through role-based access control (RBAC), without requiring app credentials. After assigning a managed identity to your web app, Azure takes care of the creation and distribution of a certificate. You don't have to worry about managing secrets or app credentials.

In this tutorial, you learn how to:

  • Create a system-assigned managed identity on a web app.
  • Add Microsoft Graph API permissions to a managed identity.
  • Call Microsoft Graph from a web app by using managed identities.

If you don't have an Azure subscription, create an Azure free account before you begin.

Prerequisites

Enable managed identity on app

If you create and publish your web app through Visual Studio, the managed identity was enabled on your app for you.

  1. In your app service, select Identity in the left pane and then select System assigned.

  2. Verify that Status is set to On. If not, select Save and then select Yes to enable the system-assigned managed identity. When the managed identity is enabled, the status is set to On and the object ID is available.

  3. Take note of the Object ID value, which you'll need in the next step.

Screenshot that shows the system-assigned identity.

Grant access to Microsoft Graph

When accessing the Microsoft Graph, the managed identity needs to have proper permissions for the operation it wants to perform. Currently, there's no option to assign such permissions through the Azure portal.

  1. Run the following script to add the requested Microsoft Graph API permissions to the managed identity service principal object.

    # Install the module. (You need admin on the machine.)
    # Install-Module AzureAD.
    
    # Your tenant ID (in the Azure portal, under Azure Active Directory > Overview).
    $TenantID="<tenant-id>"
    $resourceGroup = "securewebappresourcegroup"
    $webAppName="SecureWebApp-20201102125811"
    
    # Get the ID of the managed identity for the web app.
    $spID = (Get-AzWebApp -ResourceGroupName $resourceGroup -Name $webAppName).identity.principalid
    
    # Check the Microsoft Graph documentation for the permission you need for the operation.
    $PermissionName = "User.Read.All"
    
    Connect-AzureAD -TenantId $TenantID
    
    # Get the service principal for Microsoft Graph.
    # First result should be AppId 00000003-0000-0000-c000-000000000000
    $GraphServicePrincipal = Get-AzureADServicePrincipal -SearchString "Microsoft Graph" | Select-Object -first 1
    
    # Assign permissions to the managed identity service principal.
    $AppRole = $GraphServicePrincipal.AppRoles | `
    Where-Object {$_.Value -eq $PermissionName -and $_.AllowedMemberTypes -contains "Application"}
    
    New-AzureAdServiceAppRoleAssignment -ObjectId $spID -PrincipalId $spID `
    -ResourceId $GraphServicePrincipal.ObjectId -Id $AppRole.Id
    
  2. After executing the script, you can verify in the Azure portal that the requested API permissions are assigned to the managed identity.

  3. Go to Azure Active Directory, and then select Enterprise applications. This pane displays all the service principals in your tenant. In Managed Identities, select the service principal for the managed identity.

    If you're following this tutorial, there are two service principals with the same display name (SecureWebApp2020094113531, for example). The service principal that has a Homepage URL represents the web app in your tenant. The service principal that appears in Managed Identities should not have a Homepage URL listed and the Object ID should match the object ID value of the managed identity in the previous step.

  4. Select the service principal for the managed identity.

    Screenshot that shows the All applications option.

  5. In Overview, select Permissions, and you'll see the added permissions for Microsoft Graph.

    Screenshot that shows the Permissions pane.

Call Microsoft Graph with Node.js

Your web app now has the required permissions and also adds Microsoft Graph's client ID to the login parameters.

The DefaultAzureCredential class from @azure/identity package is used to get a token credential for your code to authorize requests to Azure Storage. Create an instance of the DefaultAzureCredential class, which uses the managed identity to fetch tokens and attach them to the service client. The following code example gets the authenticated token credential and uses it to create a service client object, which gets the users in the group.

To see this code as part of a sample application, see the:

Note

The @azure/identity package isn't required in your web app for basic authentication/authorization or to authenticate requests with Microsoft Graph. It's possible to securely call downstream APIs with only the App Service authentication/authorization module enabled.

However, the App Service authentication/authorization is designed for more basic authentication scenarios. For more complex scenarios (handling custom claims, for example), you need the @azure/identity package. There's a little more setup and configuration work in the beginning, but the @azure/identity package can run alongside the App Service authentication/authorization module. Later, when your web app needs to handle more complex scenarios, you can disable the App Service authentication/authorization module and @azure/identity will already be a part of your app.

Install client library packages

Install the @azure/identity and the @microsoft/microsoft-graph-client packages in your project with npm.

npm install @azure/identity @microsoft/microsoft-graph-client

Configure authentication information

Create an object to hold the authentication settings:

// partial code in app.js
const appSettings = {
    appCredentials: {
        clientId: process.env.WEBSITE_AUTH_CLIENT_ID, // Enter the client Id here,
        tenantId: "common", // Enter the tenant info here,
        clientSecret: process.env.MICROSOFT_PROVIDER_AUTHENTICATION_SECRET // Enter the client secret here,
    },
    authRoutes: {
        redirect: "/.auth/login/aad/callback", // Enter the redirect URI here
        unauthorized: "/unauthorized" // enter the relative path to unauthorized route
    },
}

Call Microsoft Graph on behalf of the app

The following code shows how to call Microsoft Graph controller as the app and get some user information.

// graphController.js

const graphHelper = require('../utils/graphHelper');
const { DefaultAzureCredential } = require("@azure/identity");

exports.getUsersPage = async(req, res, next) => {

    const defaultAzureCredential = new DefaultAzureCredential();
    
    try {
        // get app's access token scoped to Microsoft Graph
        const tokenResponse = await defaultAzureCredential.getToken("https://graph.microsoft.com/.default");

        // use token to create Graph client
        const graphClient = graphHelper.getAuthenticatedClient(tokenResponse.token);

        // return profiles of users in Graph
        const users = await graphClient
            .api('/users')
            .get();

        res.render('users', { user: req.session.user, users: users });   
    } catch (error) {
        next(error);
    }
}

The previous code relies on the following getAuthenticatedClient function to return Microsoft Graph client.

// utils/graphHelper.js

const graph = require('@microsoft/microsoft-graph-client');

getAuthenticatedClient = (accessToken) => {
    // Initialize Graph client
    const client = graph.Client.init({
        // Use the provided access token to authenticate requests
        authProvider: (done) => {
            done(null, accessToken);
        }
    });

    return client;
}

Clean up resources

If you're finished with this tutorial and no longer need the web app or associated resources, clean up the resources you created.

Delete the resource group

In the Azure portal, select Resource groups from the portal menu and select the resource group that contains your app service and app service plan.

Select Delete resource group to delete the resource group and all the resources.

Screenshot that shows deleting the resource group.

This command might take several minutes to run.

Delete the app registration

From the portal menu, select Azure Active Directory > App registrations. Then select the application you created. Screenshot that shows selecting app registration.

In the app registration overview, select Delete. Screenshot that shows deleting the app registration.

Next steps

In this tutorial, you learned how to:

  • Create a system-assigned managed identity on a web app.
  • Add Microsoft Graph API permissions to a managed identity.
  • Call Microsoft Graph from a web app by using managed identities.

Learn how to connect a .NET Core app, Python app, Java app, or Node.js app to a database.