Skip to content

Latest commit

 

History

History
113 lines (86 loc) · 3.73 KB

tutorial-connect-app-access-microsoft-graph-as-user-javascript.md

File metadata and controls

113 lines (86 loc) · 3.73 KB
title description services author manager ms.service ms.topic ms.date ms.author ms.reviewer ms.devlang ms.custom ms.subservice
Tutorial - Web app accesses Microsoft Graph as the user | Azure
In this tutorial, you learn how to access data in Microsoft Graph for a signed-in user.
microsoft-graph, app-service-web
rwike77
CelesteDG
azure-app-service
tutorial
03/08/2022
ryanwi
stsoneff
csharp
azureday1, devx-track-js, AppServiceConnectivity
web-apps

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

[!INCLUDE tutorial-content-above-code]

Call Microsoft Graph from Node.js

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

Install client library packages

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

npm install @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
        error: "/error", // enter the relative path to error handling route
        unauthorized: "/unauthorized" // enter the relative path to unauthorized route
    },
    protectedResources: {
        graphAPI: {
            endpoint: "https://graph.microsoft.com/v1.0/me", // resource endpoint
            scopes: ["User.Read"] // resource scopes
        },
    },
}

Call Microsoft Graph on behalf of the user

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

// controllers/graphController.js

// get the name of the app service instance from environment variables
const appServiceName = process.env.WEBSITE_SITE_NAME;

const graphHelper = require('../utils/graphHelper');

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

    try {
        // get user's access token scoped to Microsoft Graph from session
        // use token to create Graph client
        const graphClient = graphHelper.getAuthenticatedClient(req.session.protectedResources["graphAPI"].accessToken);

        // return user's profile
        const profile = await graphClient
            .api('/me')
            .get();

        res.render('profile', { isAuthenticated: req.session.isAuthenticated, profile: profile, appServiceName: appServiceName });   
    } 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;
}

[!INCLUDE second-part]