你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
了解如何从在 Azure App Service 上运行的 Web 应用访问Microsoft Graph。
你想要从 Web 应用添加对Microsoft Graph的访问权限,并作为登录用户执行一些操作。 本部分介绍如何向 Web 应用授予委派权限,以及如何从Microsoft Entra ID获取登录用户的个人资料信息。
本教程介绍如何执行下列操作:
- 向 Web 应用授予委托的权限。
- 从 Web 应用为已登录用户调用Microsoft Graph。
如果没有Azure帐户,请在开始前创建一个 free 帐户。
先决条件
- 在启用了 App 服务身份验证/授权模块的 Azure App Service 上运行的 Web 应用程序。
授予前端对调用Microsoft Graph的访问权限
在 Web 应用上启用身份验证和授权后,Web 应用将注册到Microsoft identity platform,并由Microsoft Entra应用程序提供支持。 在此步骤中,授予 Web 应用相应权限,为用户访问 Microsoft Graph。 (从技术上讲,你向 Web 应用的 Microsoft Entra 应用程序授予了访问用户的 Microsoft Graph Microsoft Entra 应用程序的权限。)
在 Microsoft Entra admin center 中,选择 Entra ID。
选择 App registrations>Owned applications> 查看此目录中的所有应用程序。 选择你的 Web 应用名称,然后选择“API 权限”。
选择添加权限,然后选择Microsoft API 和Microsoft Graph。
选择“委托的权限”,然后从列表中选择“User.Read” 。 选择“添加权限”。
对应用服务进行配置,使之返回可用的访问令牌
Web 应用现在具有作为已登录用户访问Microsoft Graph所需的权限。 在此步骤中,将配置应用服务身份验证和授权,以便提供用于访问Microsoft Graph的可用访问令牌。 对于此步骤,需要为下游服务(Microsoft Graph)添加 User.Read 权限:https://graph.microsoft.com/User.Read。
重要
如果未将应用服务配置为返回可用访问令牌,则当在代码中调用Microsoft Graph API 时,会收到 CompactToken parsing failed with error code: 80049217 错误。
转到 Azure 资源资源管理器并使用资源树找到 Web 应用。 资源 URL 应类似于 https://management.azure.com/subscriptions/subscriptionId/resourceGroups/SecureWebApp/providers/Microsoft.Web/sites/SecureWebApp20200915115914。
此时会打开Azure资源资源管理器,并在资源树中选择 Web 应用。
在页面顶部,选择Edit以启用对Azure资源的编辑。
在左侧浏览器中,向下钻取到“config”>“authsettingsV2”。
在“authsettingsV2”视图中,选择“编辑”。
找到 identityProviders -> 的“登录”部分,并添加以下 loginParameters设置:。
"loginParameters":[ "response_type=code id_token","scope=openid offline_access profile https://graph.microsoft.com/User.Read" ]"identityProviders": { "azureActiveDirectory": { "enabled": true, "login": { "loginParameters":[ "response_type=code id_token", "scope=openid offline_access profile https://graph.microsoft.com/User.Read" ] } } } },选择“PUT”,对设置进行保存。 此设置可能需要几分钟才能生效。 Web 应用现已配置为使用适当的访问令牌访问Microsoft Graph。 如果你不这样做,Microsoft Graph将返回一个错误,显示压缩令牌的格式不正确。
从 Node.js调用Microsoft Graph
Web 应用现在具有所需的权限,并且还会将Microsoft Graph的客户端 ID 添加到登录参数。
安装客户端库包
使用 npm 在项目中安装 @azure/identity 和 @microsoft/microsoft-graph-client 包。
npm install @microsoft/microsoft-graph-client
配置身份验证信息
创建一个对象以保存身份验证设置:
// 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
},
},
}
代表用户呼叫Microsoft Graph
以下代码演示如何将Microsoft Graph控制器调用为应用并获取一些用户信息。
// 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);
}
}
前面的代码依赖于以下 getAuthenticatedClient 函数返回Microsoft Graph客户端。
// 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;
}
清理资源
如果你完成了本教程(包含多个部分)中的所有步骤,那么就已在资源组中创建了应用服务、应用服务托管计划和存储帐户。 你还在 Microsoft Entra ID 中创建了一个应用注册。 如果选择了外部配置,则可能已创建新的外部租户。 如果不再需要这些资源和应用注册,请将其删除,以免继续产生费用。
本教程介绍如何执行下列操作:
- 删除在学习本教程时创建的Azure资源。
删除资源组
在 Azure 门户中,从门户菜单中选择resource groups,然后选择包含应用服务和应用服务计划的资源组。
选择“删除资源组”,删除该资源组和所有资源。
此命令可能需要几分钟才能运行。
删除应用注册
在 Microsoft Entra admin center 中,选择 App registrations。 然后,选择创建的应用程序。
在应用注册概述中,选择“删除”。
删除外部租户
如果创建了新的外部租户,则可以将其删除。 在 Microsoft Entra admin center 中,浏览到 Entra ID>Overview>Manage tenants。
选择要删除的租户,然后选择“删除”。
可能需要先完成所需的操作,然后才能删除租户。 例如,可能需要删除租户中的所有用户流和应用注册。
如果已准备好删除租户,请选择“删除”。
后续步骤
在本教程中,你了解了如何执行以下操作:
- 向 Web 应用授予委托的权限。
- 从 Web 应用为已登录用户调用Microsoft Graph。