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 |
[!INCLUDE tutorial-content-above-code]
Your web app now has the required permissions and also adds Microsoft Graph's client ID to the login parameters.
Install the @azure/identity and the @microsoft/microsoft-graph-client packages in your project with npm.
npm install @microsoft/microsoft-graph-client
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
},
},
}
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]