快速入门:实现用户登录并代表用户调用 Microsoft Graph 的 ASP.NET Core Web 应用Quickstart: ASP.NET Core web app that signs in users and calls Microsoft Graph on their behalf

在本快速入门中,你将下载并运行一个代码示例,该示例演示 ASP.NET Core Web 应用如何从任何 Azure Active Directory (Azure AD) 组织中实现用户登录,并调用 Microsoft Graph。In this quickstart, you download and run a code sample that demonstrates how an ASP.NET Core web app can sign in users from any Azure Active Directory (Azure AD) organization and calls Microsoft Graph.

有关说明,请参阅示例工作原理See How the sample works for an illustration.

先决条件Prerequisites

注册并下载快速入门应用Register and download the quickstart app

可以使用两个选项来启动快速入门应用程序:You have two options to start your quickstart application:

选项 1:注册并自动配置应用,然后下载代码示例Option 1: Register and auto configure your app and then download your code sample

  1. 转到 Azure 门户 - 应用注册快速入门体验。Go to the Azure portal - App registrations quickstart experience.
  2. 输入应用程序的名称并选择“注册”。Enter a name for your application and select Register.
  3. 遵照说明下载内容,并一键式自动配置新应用程序。Follow the instructions to download and automatically configure your new application for you in one click.

选项 2:注册并手动配置应用程序和代码示例Option 2: Register and manually configure your application and code sample

步骤 1:注册应用程序Step 1: Register your application

若要手动注册应用程序并将应用的注册信息添加到解决方案,请执行以下步骤:To register your application and add the app's registration information to your solution manually, follow these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.
  2. 如果有权访问多个租户,请使用顶部菜单中的“目录 + 订阅”筛选器 ,选择要在其中注册应用程序的租户。
  3. 搜索并选择“Azure Active Directory” 。Search for and select Azure Active Directory.
  4. 在“管理”下,选择“应用注册” > “新建注册” 。Under Manage, select App registrations > New registration.
  5. 输入应用程序的名称(例如 AspNetCoreWebAppCallsGraph-Quickstart)。Enter a Name for your application, for example AspNetCoreWebAppCallsGraph-Quickstart. 应用的用户可能会看到此名称,你稍后可对其进行更改。Users of your app might see this name, and you can change it later.
  6. 输入 https://localhost:44321/signin-oidc 的“重定向 URI”。Enter a Redirect URI of https://localhost:44321/signin-oidc.
  7. 选择“注册” 。Select Register.
  8. 在“管理”下,选择“身份验证”。 Under Manage, select Authentication.
  9. 输入前向通道注销 URL https://localhost:44321/signout-oidcEnter a Front-channel logout URL of https://localhost:44321/signout-oidc.
  10. 选择“保存”。Select Save.
  11. 在“管理”下,选择“证书和机密” > “新建客户端机密” 。Under Manage, select Certificates & secrets > New client secret.
  12. 输入描述,例如 clientsecret1Enter a Description, for example clientsecret1.
  13. 对于密码到期时间,选择“1 年”。Select In 1 year for the secret's expiration.
  14. 选择“添加”并立即记录密码值,以供后续使用 。Select Add and immediately record the secret's Value for use in a later step. 此密码值不会重新显示,也无法通过任何其他方式检索。The secret value is never displayed again and is irretrievable by any other means. 将此值记录在安全位置,就像记录任何密码一样。Record it in a secure location as you would any password.

步骤 1:在 Azure 门户中配置应用程序Step 1: Configure your application in the Azure portal

要使本快速入门的示例代码正常运行,请在注册应用时提供重定向 URI https://localhost:44321/signin-oidc 和前向通道注销 URL https://localhost:44321/signout-oidcFor the code sample in this quickstart to work, add a Redirect URI of https://localhost:44321/signin-oidc and Front-channel logout URL of https://localhost:44321/signout-oidc in the app registration.

已配置 应用程序已使用这些属性进行配置。Already configured Your application is configured with these attributes.

步骤 2:下载 ASP.NET Core 项目Step 2: Download the ASP.NET Core project

运行该项目。Run the project.

步骤 3:应用已配置并可以运行Step 3: Your app is configured and ready to run

我们已经为项目配置了应用属性的值,并且该项目已准备好运行。We have configured your project with values of your app's properties and it's ready to run.

备注

Enter_the_Supported_Account_Info_Here

步骤 3:配置 ASP.NET Core 项目Step 3: Configure your ASP.NET Core project

  1. 将 .zip 存档解压缩到驱动器根附近的本地文件夹中。Extract the .zip archive into a local folder near the root of your drive. 例如,解压缩到 C:\Azure-Samples。For example, into C:\Azure-Samples.

  2. 在 Visual Studio 2019 中打开该解决方案。Open the solution in Visual Studio 2019.

  3. 打开 appsettings.json 文件,并修改以下内容:Open the appsettings.json file and modify the following:

    "ClientId": "Enter_the_Application_Id_here",
    "TenantId": "common",
    "clientSecret": "Enter_the_Client_Secret_Here"
    
    • Enter_the_Application_Id_here 替换为在 Azure 门户中注册的应用程序的“应用程序(客户端) ID”。Replace Enter_the_Application_Id_here with the Application (client) ID of the application you registered in the Azure portal. 可以在应用的“概览”页中找到“应用程序(客户端) ID”。You can find Application (client) ID in the app's Overview page.
    • common 替换为以下其中一项:Replace common with one of the following:
      • 如果应用程序支持“仅限此组织目录中的帐户”,请将此值替换为“目录(租户) ID”(GUID) 或“租户名称”(例如 contoso.partner.onmschina.cn) 。If your application supports Accounts in this organizational directory only, replace this value with the Directory (tenant) ID (a GUID) or tenant name (for example, contoso.partner.onmschina.cn). 你可以在应用的”概述”页上找到“目录(租户) ID” 。You can find the Directory (tenant) ID on the app's Overview page.
      • 如果应用程序支持“任何组织目录中的帐户”,请将该值替换为organizationsIf your application supports Accounts in any organizational directory, replace this value with organizations
    • Enter_the_Client_Secret_Here 替换为在先前步骤中创建并记录的客户端机密。Replace Enter_the_Client_Secret_Here with the Client secret you created and recorded in an earlier step.

在此快速入门中,请不要更改 appsettings.json 文件中的任何其他值。For this quickstart, don't change any other values in the appsettings.json file.

步骤 4:生成并运行应用程序Step 4: Build and run the application

通过选择“调试”菜单 >“开始调试”,或按 F5 键在 Visual Studio 中构建和运行应用 。Build and run the app in Visual Studio by selecting the Debug menu > Start Debugging, or by pressing the F5 key.

系统会提示你输入凭据,然后要求你同意应用所需的权限。You're prompted for your credentials, and then asked to consent to the permissions your app requires. 在同意提示上选择“接受”。Select Accept on the consent prompt.

“同意”对话框,显示应用从 > 用户请求的权限

同意请求的权限后,应用将显示你已使用 Azure Active Directory 凭据成功登录,并且你会在页面的“API 结果”部分中看到你的电子邮件地址。After consenting to the requested permissions, the app displays that you've successfully logged in using your Azure Active Directory credentials, and you'll see your email address in the "Api result" section of the page. 它是使用 Microsoft Graph 提取的。This was extracted using Microsoft Graph.

Web 浏览器显示正在运行的 web 应用和登录的用户

关于代码About the code

本部分概述了实现用户登录并代表用户调用 Microsoft Graph API 所需的代码。This section gives an overview of the code required to sign in users and call the Microsoft Graph API on their behalf. 阅读本概述对于了解代码的工作原理、主要参数非常有用,如果你想要将登录功能添加到现有 ASP.NET Core 应用程序并调用 Microsoft Graph,阅读本概述也非常有用。This overview can be useful to understand how the code works, main arguments, and also if you want to add sign-in to an existing ASP.NET Core application and call Microsoft Graph. 它使用了 Microsoft.Identity.Web,这是 MSAL.NET 的包装器。It uses Microsoft.Identity.Web, which is a wrapper around MSAL.NET.

示例工作原理How the sample works

显示本快速入门生成的示例应用的工作原理

Startup 类Startup class

Microsoft.AspNetCore.Authentication 中间件使用主机进程初始化时执行的 Startup 类:The Microsoft.AspNetCore.Authentication middleware uses a Startup class that's executed when the hosting process initializes:

  // Get the scopes from the configuration (appsettings.json)
  var initialScopes = Configuration.GetValue<string>("DownstreamApi:Scopes")?.Split(' ');

  public void ConfigureServices(IServiceCollection services)
  {
      // Add sign-in with Microsoft
      services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))

            // Add the possibility of acquiring a token to call a protected web API
            .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)

                // Enables controllers and pages to get GraphServiceClient by dependency injection
                // And use an in memory token cache
                .AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
                .AddInMemoryTokenCaches();

      services.AddControllersWithViews(options =>
      {
          var policy = new AuthorizationPolicyBuilder()
              .RequireAuthenticatedUser()
              .Build();
          options.Filters.Add(new AuthorizeFilter(policy));
      });

      // Enables a UI and controller for sign in and sign out.
      services.AddRazorPages()
          .AddMicrosoftIdentityUI();
  }

方法 AddAuthentication() 配置该服务以添加基于 Cookie 的身份验证,此身份验证在浏览器方案中使用,并用于设置 OpenID Connect 质询。The AddAuthentication() method configures the service to add cookie-based authentication, which is used in browser scenarios and to set the challenge to OpenID Connect.

包含 .AddMicrosoftIdentityWebApp 的行可向应用程序添加 Microsoft 标识平台身份验证。The line containing .AddMicrosoftIdentityWebApp adds the Microsoft identity platform authentication to your application. 这是由 Microsoft.Identity.Web 提供的。This is provided by Microsoft.Identity.Web. 然后对其进行配置,使其根据 appsettings.json 配置文件的 AzureAD 部分中的信息,使用 Microsoft 标识平台登录:It's then configured to sign in using the Microsoft identity platform based on the information in the AzureAD section of the appsettings.json configuration file:

appsettings.json 密钥appsettings.json key 说明Description
ClientId Azure 门户中注册的应用程序的“应用程序(客户端) ID”。Application (client) ID of the application registered in the Azure portal.
Instance 用户进行身份验证时使用的安全令牌服务 (STS) 终结点。Security token service (STS) endpoint for the user to authenticate. 此值通常为 https://login.partner.microsoftonline.cn/This value is typically https://login.partner.microsoftonline.cn/.
TenantId 该值是租户的名称或其租户 ID (GUID),或者是 common(如果使用工作帐户或学校帐户进行用户登录)。Name of your tenant or its tenant ID (a GUID), or common to sign in users with work or school accounts.

应用程序使用 EnableTokenAcquisitionToCallDownstreamApi 方法可以获取令牌来调用受保护的 Web API。The EnableTokenAcquisitionToCallDownstreamApi method enables your application to acquire a token to call protected web APIs. 控制器或 Razor 页使用 AddMicrosoftGraph 可直接(通过依赖项注入)让 GraphServiceClient 受益,而应用使用 AddInMemoryTokenCaches 方法可受益于令牌缓存。AddMicrosoftGraph enables your controllers or Razor pages to benefit directly the GraphServiceClient (by dependency injection) and the AddInMemoryTokenCaches methods enables your app to benefit from a token cache.

Configure() 方法包含两个重要的方法 app.UseAuthentication()app.UseAuthorization(),这些方法实现了命名功能。The Configure() method contains two important methods, app.UseAuthentication() and app.UseAuthorization(), that enable their named functionality. 此外,在 Configure() 方法中,必须至少调用一次 endpoints.MapControllerRoute() 或调用 endpoints.MapControllers()来注册 Microsoft Identity Web 的路由。Also in the Configure() method, you must register Microsoft Identity Web's routes with at least one call to endpoints.MapControllerRoute() or a call to endpoints.MapControllers().

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{

    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();
});

// endpoints.MapControllers(); // REQUIRED if MapControllerRoute() isn't called.

保护控制器或控制器的方法Protect a controller or a controller's method

可以通过将 [Authorize] 属性应用于控制器的类或其一个或多个方法来保护控制器或其方法。You can protect a controller or its methods by applying the [Authorize] attribute to the controller's class or one or more of its methods. [Authorize] 属性只允许通过身份验证的用户,从而限制了访问。This [Authorize] attribute restricts access by allowing only authenticated users. 如果用户尚未通过身份验证,可以启动身份验证质询来访问控制器。If the user isn't already authenticated, an authentication challenge can be started to access the controller. 本快速入门从配置文件中读取范围:In this quickstart, the scopes are read from the configuration file:

[AuthorizeForScopes(ScopeKeySection = "DownstreamApi:Scopes")]
public async Task<IActionResult> Index()
{
    var user = await _graphServiceClient.Me.Request().GetAsync();
    ViewData["ApiResult"] = user.DisplayName;

    return View();
}

帮助和支持Help and support

如果需要帮助、需要报告问题,或者需要详细了解支持选项,请参阅面向开发人员的帮助和支持If you need help, want to report an issue, or want to learn about your support options, see Help and support for developers.

后续步骤Next steps

包含本快速入门中引用的 ASP.NET Core 代码示例的 GitHub 存储库包含说明和更多代码示例,这些示例向你展示如何:The GitHub repo that contains the ASP.NET Core code sample referenced in this quickstart includes instructions and more code samples that show you how to:

  • 向新的 ASP.NET Core Web 应用程序添加身份验证Add authentication to a new ASP.NET Core Web application
  • 调用 Microsoft Graph、其他 Microsoft API 或你自己的 Web APICall Microsoft Graph, other Microsoft APIs, or your own web APIs
  • 添加授权Add authorization
  • 在国家云中或使用社会标识实现用户登录Sign in users in national clouds or with social identities