快速入门:向 ASP.NET Core Web 应用添加 Microsoft 登录功能Quickstart: Add sign-in with Microsoft to an ASP.NET Core web app

在本快速入门中,你将下载并运行一个代码示例,该示例演示 ASP.NET Core Web 应用如何从任何 Azure Active Directory (Azure AD) 组织中登录用户。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.

下图显示了该示例应用的工作原理:The following diagram shows how the sample app works:

示例应用中 Web 浏览器、Web 应用和 Microsoft 标识平台之间的交互关系图。

先决条件Prerequisites

注册和下载应用Register and download the app

可以通过两种方法开始生成应用程序:自动或手动配置。You have two options to start building your application: automatic or manual configuration.

自动配置Automatic configuration

如果要自动配置应用,然后下载代码示例,请执行以下步骤:If you want to automatically configure your app and then download the code sample, follow these steps:

  1. 转到 Azure 门户页面进行应用注册Go to the Azure portal page for app registration.
  2. 输入应用程序的名称并选择“注册”。Enter a name for your application and select Register.
  3. 遵循说明下载内容,并一键自动配置新应用程序。Follow the instructions to download and automatically configure your new application in one click.

手动配置Manual configuration

如果要手动配置应用程序和代码示例,请执行以下过程。If you want to manually configure your application and code sample, use the following procedures.

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

  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. 对于“名称”,请输入应用程序名称。For Name, enter a name for your application. 例如,输入 AspNetCore-Quickstart。For example, enter AspNetCore-Quickstart. 应用的用户会看到此名称,你稍后可对其进行更改。Users of your app will see this name, and you can change it later.
  6. 对于“重定向 URI”,请输入 https://localhost:44321/signin-oidc 。For Redirect URI, enter https://localhost:44321/signin-oidc.
  7. 选择“注册” 。Select Register.
  8. 在“管理”下,选择“身份验证”。 Under Manage, select Authentication.
  9. 对于“前通道注销 URL”,请输入 https://localhost:44321/signout-oidc 。For Front-channel logout URL, enter https://localhost:44321/signout-oidc.
  10. 在“隐式授权和混合流”下,选择“ID 令牌” 。Under Implicit grant and hybrid flows, select ID tokens.
  11. 选择“保存”。Select Save.

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

为使此快速入门中的代码示例正常运行:For the code sample in this quickstart to work:

  • 对于“重定向 URI”,请输入 https://localhost:44321/ 和 https://localhost:44321/signin-oidc 。For Redirect URI, enter https://localhost:44321/ and https://localhost:44321/signin-oidc.
  • 对于“前通道注销 URL”,请输入 https://localhost:44321/signout-oidc 。For Front-channel logout URL, enter https://localhost:44321/signout-oidc.

授权终结点将发出请求 ID 令牌。The authorization endpoint will issue request ID tokens.

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

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

运行该项目。Run the project.

提示

为了避免在 Windows 中出现路径长度限制导致的错误,建议将存档解压或将存储库克隆到驱动器根附近的目录中。To avoid errors caused by path length limitations in Windows, we recommend extracting the archive or cloning the repository into a directory near the root of your drive.

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

我们已经为项目配置了应用属性的值,并且该项目已准备好运行。We've 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, extract into C:\Azure-Samples.

    建议将存档解压到驱动器根附近的目录中,以避免在 Windows 上出现路径长度限制导致的错误。We recommend extracting the archive into a directory near the root of your drive to avoid errors caused by path length limitations on Windows.

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

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

    "Domain": "Enter the domain of your tenant, e.g. contoso.partner.onmschina.cn",
    "ClientId": "Enter_the_Application_Id_here",
    "TenantId": "common",
    
    • Enter_the_Application_Id_here 替换为在 Azure 门户中注册的应用程序的应用程序(客户端)ID。Replace Enter_the_Application_Id_here with the application (client) ID of the application that you registered in the Azure portal. 可以在应用的“概述”页中找到“应用程序(客户端) ID”值 。You can find the Application (client) ID value on 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 the tenant name (for example, contoso.partner.onmschina.cn). 可以在应用的“概述”页上找到“目录(租户) ID”值 。You can find the Directory (tenant) ID value on the app's Overview page.
      • 如果应用程序支持“任何组织目录中的帐户”,请将该值替换为 organizationsIf your application supports Accounts in any organizational directory, replace this value with organizations.

在此快速入门中,请不要更改 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 that your app requires. 在同意提示上选择“接受”。Select Accept on the consent prompt.

“同意”对话框的屏幕截图,显示应用正在向用户请求的权限。

同意请求的权限后,应用将显示你已使用 Azure Active Directory 凭据成功登录。After you consent to the requested permissions, the app displays that you've successfully signed in with your Azure Active Directory credentials.

Web 浏览器的屏幕截图,显示正在运行的 Web 应用和已登录的用户。

详细信息More information

本部分概述了使用户登录所需的代码。This section gives an overview of the code required to sign in users. 此概述对于了解代码的工作原理、主要参数是什么,以及如何向现有 ASP.NET Core 应用程序添加登录非常有用。This overview can be useful to understand how the code works, what the main arguments are, and how to add sign-in to an existing ASP.NET Core application.

示例工作原理How the sample works

示例应用中 Web 浏览器、Web 应用和 Microsoft 标识平台之间的交互关系图。

Startup 类Startup class

Microsoft.AspNetCore.Authentication 中间件使用托管进程启动时运行的 Startup 类:The Microsoft.AspNetCore.Authentication middleware uses a Startup class that's run when the hosting process starts:

  public void ConfigureServices(IServiceCollection services)
  {
      services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
          .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

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

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

包含 .AddMicrosoftIdentityWebApp 的行可向应用程序添加 Microsoft 标识平台身份验证。The line that contains .AddMicrosoftIdentityWebApp adds Microsoft identity platform authentication to your application. 然后对应用程序进行配置,使其根据 appsettings.json 配置文件的 AzureAD 部分中的信息登录用户:The application is then configured to sign in users based on the following 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/,指示 Azure 中国云。This value is typically https://login.partner.microsoftonline.cn/, indicating the Azure China cloud.
TenantId 此值是租户的名称或租户 ID (GUID),或者是 common(如果使用工作帐户或学校帐户进行用户登录)。Name of your tenant or the tenant ID (a GUID), or common to sign in users with work or school accounts accounts.

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 标识 Web 路由:Also in the Configure() method, you must register Microsoft Identity Web 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.

用于保护控制器或方法的属性Attribute for protecting a controller or methods

可以使用 [Authorize] 属性保护控制器或控制器方法。You can protect a controller or controller methods by using the [Authorize] attribute. 此属性只允许经过身份验证的用户,从而限制对控制器或方法的访问。This attribute restricts access to the controller or methods by allowing only authenticated users. 如果用户尚未通过身份验证,可以启动身份验证质询来访问控制器。An authentication challenge can then be started to access the controller if the user isn't authenticated.

帮助和支持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 this ASP.NET Core tutorial 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 API。Call Microsoft Graph, other Microsoft APIs, or your own web APIs.
  • 添加授权。Add authorization.
  • 在国家云中或使用社会标识实现用户登录。Sign in users in national clouds or with social identities.