教程:以用户身份从安全的应用访问 Microsoft GraphTutorial: Access Microsoft Graph from a secured app as the user

了解如何从 Azure 应用服务上运行的 Web 应用访问 Microsoft Graph。Learn how to access Microsoft Graph from a web app running on Azure App Service.

显示如何访问 Microsoft Graph 流的示意图。

你希望从 Web 应用添加对 Microsoft Graph 的访问权限,并以已登录用户的身份执行一些操作。You want to add access to Microsoft Graph from your web app and perform some action as the signed-in user. 本部分介绍如何向 Web 应用授予委托的权限,以及如何从 Azure Active Directory (Azure AD) 获取已登录用户的配置文件信息。This section describes how to grant delegated permissions to the web app and get the signed-in user's profile information from Azure Active Directory (Azure AD).

在本教程中,你将了解:In this tutorial, you learn how to:

  • 向 Web 应用授予委托的权限。Grant delegated permissions to a web app.
  • 为已登录的用户从 Web 应用调用 Microsoft Graph。Call Microsoft Graph from a web app for a signed-in user.

如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin.

先决条件Prerequisites

授予前端访问权限以调用 Microsoft GraphGrant front-end access to call Microsoft Graph

现在,你已在 Web 应用上启用了身份验证和授权,该 Web 应用在 Microsoft 标识平台上注册,并由 Azure AD 应用程序提供支持。Now that you've enabled authentication and authorization on your web app, the web app is registered with the Microsoft identity platform and is backed by an Azure AD application. 在此步骤中,授予 Web 应用相应权限,为用户访问 Microsoft Graph。In this step, you give the web app permissions to access Microsoft Graph for the user. (严格说来,授予 Web 应用的 Azure AD 应用程序相应权限,为用户访问 Microsoft Graph Azure AD 应用程序。)(Technically, you give the web app's Azure AD application the permissions to access the Microsoft Graph Azure AD application for the user.)

Azure 门户菜单中,选择“Azure Active Directory”,或在任意页面中搜索并选择“Azure Active Directory”。In the Azure portal menu, select Azure Active Directory or search for and select Azure Active Directory from any page.

选择“应用注册” > “拥有的应用程序” > “查看此目录中的所有应用程序”。Select App registrations > Owned applications > View all applications in this directory. 选择你的 Web 应用名称,然后选择“API 权限”。Select your web app name, and then select API permissions.

依次选择“添加权限”、“Microsoft API”和“Microsoft Graph”。Select Add a permission, and then select Microsoft APIs and Microsoft Graph.

选择“委托的权限”,然后从列表中选择“User.Read” 。Select Delegated permissions, and then select User.Read from the list. 选择“添加权限”。Select Add permissions.

对应用服务进行配置,使之返回可用的访问令牌Configure App Service to return a usable access token

Web 应用现在具有以已登录用户身份访问 Microsoft Graph 所需的权限。The web app now has the required permissions to access Microsoft Graph as the signed-in user. 在此步骤中,配置应用服务身份验证和授权,以便获取用于访问 Microsoft Graph 的可用访问令牌。In this step, you configure App Service authentication and authorization to give you a usable access token for accessing Microsoft Graph. 对于此步骤,需要下游服务 (Microsoft Graph) 的客户端/应用程序 ID。For this step, you need the client/app ID of the downstream service (Microsoft Graph). Microsoft Graph 的应用 ID 是 00000003-0000-0000-c000-000000000000。The app ID for Microsoft Graph is 00000003-0000-0000-c000-000000000000.

重要

如果未将应用服务配置为返回可用的访问令牌,则在代码中调用 Microsoft 图形 API 时会收到 CompactToken parsing failed with error code: 80049217 错误。If you don't configure App Service to return a usable access token, you receive a CompactToken parsing failed with error code: 80049217 error when you call Microsoft Graph APIs in your code.

转到 Azure 资源浏览器并使用资源树找到 Web 应用。Go to Azure Resource Explorer and using the resource tree, locate your web app. 资源 URL 应类似于 https://resources.azure.com/subscriptions/subscription-id/resourceGroups/SecureWebApp/providers/Microsoft.Web/sites/SecureWebApp20200915115914The resource URL should be similar to https://resources.azure.com/subscriptions/subscription-id/resourceGroups/SecureWebApp/providers/Microsoft.Web/sites/SecureWebApp20200915115914.

此时会打开 Azure 资源浏览器,Web 应用在资源树中处于选中状态。The Azure Resource Explorer is now opened with your web app selected in the resource tree. 在页面顶部选择“读/写”,以便启用编辑 Azure 资源的功能。At the top of the page, select Read/Write to enable editing of your Azure resources.

在左侧浏览器中,向下钻取到“config” > “authsettings”。In the left browser, drill down to config > authsettings.

在“authsettings”视图中,选择“编辑”。In the authsettings view, select Edit. 使用复制的客户端 ID 将 additionalLoginParams 设置为以下 JSON 字符串。Set additionalLoginParams to the following JSON string by using the client ID you copied.

"additionalLoginParams": ["response_type=code id_token","resource=00000003-0000-0000-c000-000000000000"],

选择“PUT”,对设置进行保存。Save your settings by selecting PUT. 此设置可能需要几分钟才能生效。This setting can take several minutes to take effect. 现在,Web 应用已配置为使用适当的访问令牌访问 Microsoft Graph。Your web app is now configured to access Microsoft Graph with a proper access token. 如果未进行设置,Microsoft Graph 将返回一个错误,指示压缩令牌的格式不正确。If you don't, Microsoft Graph returns an error saying that the format of the compact token is incorrect.

调用 Microsoft Graph (.NET)Call Microsoft Graph (.NET)

Web 应用现在具有所需的权限,并且还将 Microsoft Graph 的客户端 ID 添加到登录参数中。Your web app now has the required permissions and also adds Microsoft Graph's client ID to the login parameters. 使用 Microsoft.Identity.Web 库,Web 应用将获取一个访问令牌,用于向 Microsoft Graph 进行身份验证。Using the Microsoft.Identity.Web library, the web app gets an access token for authentication with Microsoft Graph. 在 1.2.0 版和更高版本中,Microsoft.Identity.Web 库与应用服务身份验证/授权模块集成,且可与之一起运行。In version 1.2.0 and later, the Microsoft.Identity.Web library integrates with and can run alongside the App Service authentication/authorization module. Microsoft.Identity.Web 检测到该 Web 应用托管在应用服务中,并从应用服务身份验证/授权模块获取访问令牌。Microsoft.Identity.Web detects that the web app is hosted in App Service and gets the access token from the App Service authentication/authorization module. 然后,使用 Microsoft Graph API 将访问令牌传递给经过身份验证的请求。The access token is then passed along to authenticated requests with the Microsoft Graph API.

若要查看作为示例应用程序一部分的代码,请参阅 GitHub 上的示例To see this code as part of a sample application, see the sample on GitHub.

备注

Web 应用无需 Microsoft.Identity.Web 库即可进行基础身份验证/授权或向 Microsoft Graph 验证请求。The Microsoft.Identity.Web library isn't required in your web app for basic authentication/authorization or to authenticate requests with Microsoft Graph.

但是,应用服务身份验证/授权旨在用于更基本的身份验证场景。However, the App Service authentication/authorization is designed for more basic authentication scenarios. 对于更复杂的场景(例如处理自定义声明),需要 Microsoft.Identity.Web 库或 Microsoft 身份验证库For more complex scenarios (handling custom claims, for example), you need the Microsoft.Identity.Web library or Microsoft Authentication Library. 在一开始就有更多的设置和配置工作,但 Microsoft.Identity.Web 库可与应用服务身份验证/授权模块同时运行。There's a little more setup and configuration work in the beginning, but the Microsoft.Identity.Web library can run alongside the App Service authentication/authorization module. 当 Web 应用以后需要处理更复杂的场景时,你可以禁用应用服务身份验证/授权模块,而 Microsoft.Identity.Web 将已是应用的一部分。Later, when your web app needs to handle more complex scenarios, you can disable the App Service authentication/authorization module and Microsoft.Identity.Web will already be a part of your app.

安装客户端库包Install client library packages

使用 .NET Core 命令行接口或 Visual Studio 中的包管理器控制台,在项目中安装 Microsoft.Identity.WebMicrosoft.Graph NuGet 包。Install the Microsoft.Identity.Web and Microsoft.Graph NuGet packages in your project by using the .NET Core command-line interface or the Package Manager Console in Visual Studio.

打开一个命令行,并切换到包含项目文件的目录。Open a command line, and switch to the directory that contains your project file.

运行安装命令。Run the install commands.

dotnet add package Microsoft.Graph

dotnet add package Microsoft.Identity.Web

Startup.csStartup.cs

在 Startup.cs 文件中,AddMicrosoftIdentityWebApp 方法会将 Microsoft.Identity.Web 添加到 Web 应用。In the Startup.cs file, the AddMicrosoftIdentityWebApp method adds Microsoft.Identity.Web to your web app. AddMicrosoftGraph 方法会添加 Microsoft Graph 支持。The AddMicrosoftGraph method adds Microsoft Graph support.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;

// Some code omitted for brevity.
public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
                    .EnableTokenAcquisitionToCallDownstreamApi()
                        .AddMicrosoftGraph(Configuration.GetSection("Graph"))
                        .AddInMemoryTokenCaches();

        services.AddRazorPages();
    }
}

appsettings.jsonappsettings.json

AzureAd 指定 Microsoft.Identity.Web 库的配置。AzureAd specifies the configuration for the Microsoft.Identity.Web library. Azure 门户中,从门户菜单中选择“Azure Active Directory”,然后选择“应用注册” 。In the Azure portal, select Azure Active Directory from the portal menu and then select App registrations. 选择启用应用服务身份验证/授权模块时创建的应用注册。Select the app registration created when you enabled the App Service authentication/authorization module. (该应用注册应具有与 Web 应用相同的名称。)可在应用注册概述页面中找到租户 ID 和客户 ID。(The app registration should have the same name as your web app.) You can find the tenant ID and client ID in the app registration overview page. 可以在租户的 Azure AD 概述页面中找到域名。The domain name can be found in the Azure AD overview page for your tenant.

Graph 会指定 Microsoft Graph 终结点和应用所需的初始范围。Graph specifies the Microsoft Graph endpoint and the initial scopes needed by the app.

{
  "AzureAd": {
    "Instance": "https://login.partner.microsoftonline.cn/",
    "Domain": "fourthcoffeetest.partner.onmschina.cn",
    "TenantId": "[tenant-id]",
    "ClientId": "[client-id]",
    // To call an API
    "ClientSecret": "[secret-from-portal]", // Not required by this scenario
    "CallbackPath": "/signin-oidc"
  },

  "Graph": {
    "BaseUrl": "https://graph.chinacloudapi.cn/v1.0",
    "Scopes": "user.read"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Index.cshtml.csIndex.cshtml.cs

下面的示例演示如何以已登录用户身份调用 Microsoft Graph 并获取一些用户信息。The following example shows how to call Microsoft Graph as the signed-in user and get some user information. GraphServiceClient 对象已注入到控制器中,并且 Microsoft.Identity.Web 库已为你配置了身份验证。The GraphServiceClient object is injected into the controller, and authentication has been configured for you by the Microsoft.Identity.Web library.

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Graph;
using System.IO;
using Microsoft.Identity.Web;
using Microsoft.Extensions.Logging;

// Some code omitted for brevity.

[AuthorizeForScopes(Scopes = new[] { "user.read" })]
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;
    private readonly GraphServiceClient _graphServiceClient;

    public IndexModel(ILogger<IndexModel> logger, GraphServiceClient graphServiceClient)
    {
        _logger = logger;
        _graphServiceClient = graphServiceClient;
    }

    public async Task OnGetAsync()
    {
        try
        {
            var user = await _graphServiceClient.Me.Request().GetAsync();
            ViewData["Me"] = user;
            ViewData["name"] = user.DisplayName;

            using (var photoStream = await _graphServiceClient.Me.Photo.Content.Request().GetAsync())
            {
                byte[] photoByte = ((MemoryStream)photoStream).ToArray();
                ViewData["photo"] = Convert.ToBase64String(photoByte);
            }
        }
        catch (Exception ex)
        {
            ViewData["photo"] = null;
        }
    }
}

清理资源Clean up resources

如果已完成本教程,并且不再需要 Web 应用或相关资源,请清理创建的资源If you're finished with this tutorial and no longer need the web app or associated resources, clean up the resources you created.

后续步骤Next steps

在本教程中,你将了解:In this tutorial, you learned how to:

  • 向 Web 应用授予委托的权限。Grant delegated permissions to a web app.
  • 为已登录的用户从 Web 应用调用 Microsoft Graph。Call Microsoft Graph from a web app for a signed-in user.