快速入门:向 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 use a code sample to learn how an ASP.NET Core web app can sign in work and school accounts from any Azure Active Directory (Azure AD) instance. (有关说明,请参阅示例工作原理。)(See How the sample works for an illustration.)

注册并下载快速入门应用Register and download your 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.
  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 manually add the app's registration information to your solution, follow these steps:

  1. 使用工作或学校帐户登录到 Azure 门户Sign in to the Azure portal using a work or school account.
  2. 如果你的帐户有权访问多个租户,请在右上角选择该帐户,并将门户会话设置为所需的 Azure AD 租户。If your account gives you access to more than one tenant, select your account in the top right corner, and set your portal session to the desired Azure AD tenant.
  3. 导航到面向开发人员的 Microsoft 标识平台的应用注册页。Navigate to the Microsoft identity platform for developers App registrations page.
  4. 选择“新注册”。Select New registration.
  5. “注册应用程序”页出现后,请输入应用程序的注册信息:When the Register an application page appears, enter your application's registration information:
    • 在“名称”部分输入一个会显示给应用用户的有意义的应用程序名称,例如 AspNetCore-QuickstartIn the Name section, enter a meaningful application name that will be displayed to users of the app, for example AspNetCore-Quickstart.
    • 在“重定向 URI”中添加 https://localhost:44321/,然后选择“注册”。In Redirect URI, add https://localhost:44321/, and select Register.
  6. 选择“身份验证”菜单,然后添加以下信息:Select the Authentication menu, and then add the following information:
    • 在“重定向 URI”中添加 https://localhost:44321/signin-oidc,然后选择“保存”。In Redirect URIs, add https://localhost:44321/signin-oidc, and select Save.
    • 在“高级设置”部分,将“注销 URL”设置为 https://localhost:44321/signout-oidcIn the Advanced settings section, set Logout URL to https://localhost:44321/signout-oidc.
    • 在“隐式授权”下,勾选“ID 令牌”。Under Implicit grant, check ID tokens.
    • 选择“保存”。Select Save.

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

为使此快速入门中的代码示例正常运行,需将回复 URL 添加为 https://localhost:44321/https://localhost:44321/signin-oidc,将注销 URL 添加为 https://localhost:44321/signout-oidc,并请求将由授权终结点颁发的 ID 令牌。For the code sample for this quickstart to work, you need to add reply URLs as https://localhost:44321/ and https://localhost:44321/signin-oidc, add the Logout URL as https://localhost:44321/signout-oidc, and request ID tokens to be issued by the authorization endpoint.

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

步骤 2:下载 ASP.NET Core 项目Step 2: Download your 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: Run your ASP.NET Core project

  1. 将 zip 文件提取到根文件夹中的本地文件夹(例如,C:\Azure-SamplesExtract the zip file to a local folder within the root folder - for example, C:\Azure-Samples

  2. 在 IDE 中打开解决方案Open the solution in your IDE

  3. 编辑 appsettings.json 文件。Edit the appsettings.json file. 查找 ClientId 并使用你注册的应用程序的“应用程序 (客户端) ID”值更新 ClientId 的值。Find ClientId and update the value of ClientId with the Application (client) ID value of the application you registered.

    "ClientId": "Enter_the_Application_Id_here"
    "TenantId": "Enter_the_Tenant_Info_Here"
    

其中:Where:

  • Enter_the_Application_Id_here - 在 Azure 门户中注册的应用程序的应用程序(客户端) IDEnter_the_Application_Id_here - is the Application (client) ID for the application you registered in the Azure portal. 可以在应用的“概览”页中找到“应用程序(客户端) ID”。You can find Application (client) ID in the app's Overview page.
  • Enter_the_Tenant_Info_Here - 以下选项之一:Enter_the_Tenant_Info_Here - is one of the following options:
    • 如果应用程序支持“仅限此组织目录中的帐户”,请将该值替换为租户 ID租户名称(例如 contoso.microsoft.com)If your application supports Accounts in this organizational directory only, replace this value with the Tenant ID or Tenant name (for example, contoso.microsoft.com)
    • 如果应用程序支持“任何组织目录中的帐户”,请将该值替换为organizationsIf your application supports Accounts in any organizational directory, replace this value with organizations

提示

若要查找“应用程序(客户端) ID”、“目录(租户) ID”和“支持的帐户类型”的值,请转到 Azure 门户中应用的“概述”页。 To find the values of Application (client) ID, Directory (tenant) ID, and Supported account types, go to the app's Overview page in the Azure portal.

详细信息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, main arguments, and also if you want to add sign-in to an existing ASP.NET Core application.

示例工作原理How the sample works

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

Startup 类Startup class

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

public void ConfigureServices(IServiceCollection services)
{
  services.Configure<CookiePolicyOptions>(options =>
  {
    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
  });

  services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
          .AddAzureAD(options => Configuration.Bind("AzureAd", options));

  services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
  {
    options.Authority = options.Authority + "/v2.0/";         // Microsoft identity platform

    options.TokenValidationParameters.ValidateIssuer = false; // accept several tenants (here simplified)
  });

  services.AddMvc(options =>
  {
     var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
     options.Filters.Add(new AuthorizeFilter(policy));
  })
  .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

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

包含 .AddAzureAd 的行可向应用程序添加 Microsoft 标识平台身份验证。The line containing .AddAzureAd adds the Microsoft identity platform authentication to your application. 然后,它会被配置为使用 Microsoft 标识平台终结点登录。It's then configured to sign in using the Microsoft identity platform endpoint.

其中Where 说明Description
ClientIdClientId Azure 门户中注册的应用程序的应用程序(客户端)ID。Application (client) ID from the application registered in the Azure portal.
颁发机构Authority 用户要进行身份验证的 STS 终结点。The STS endpoint for the user to authenticate. 对于公有云,此项通常为 https://login.partner.microsoftonline.cn/{tenant}/v2.0,其中 {tenant} 是租户名称、租户 ID 或者引用常用终结点(用于多租户应用程序)的 commonUsually, this is https://login.partner.microsoftonline.cn/{tenant}/v2.0 for public cloud, where {tenant} is the name of your tenant or your tenant ID, or common for a reference to the common endpoint (used for multi-tenant applications)
TokenValidationParametersTokenValidationParameters 用于令牌验证的参数列表。A list of parameters for token validation. 在这种情况下,ValidateIssuer 设置为 false,以指示它可以接受来自任何工作或学校帐户的登录。In this case, ValidateIssuer is set to false to indicate that it can accept sign-ins from any work or school accounts.

备注

在本快速入门中,设置 ValidateIssuer = false 是一种简化操作。Setting ValidateIssuer = false is a simplification for this quickstart. 在实际应用程序中,需验证颁发者。In real applications you need to validate the issuer. 查看示例,了解如何执行该操作。See the samples to understand how to do that.

另请注意 Configure 方法,其中包含两个重要方法:app.UseCookiePolicy()app.UseAuthentication()Also note the Configure method which contains two important methods: app.UseCookiePolicy() and app.UseAuthentication()

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    // more core
    app.UseCookiePolicy();
    app.UseAuthentication();
    // more core
}

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

可以使用 [Authorize] 属性保护控制器或控制器方法。You can protect a controller or controller methods using the [Authorize] attribute. 此属性通过仅允许经过身份验证的用户,来限制对控制器或方法的访问,这意味着如果用户未经身份验证,则可以启动身份验证质询来访问控制器。This attribute restricts access to the controller or methods by only allowing authenticated users, which means that authentication challenge can 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 would like to learn about your support options, see Help and support for developers.

后续步骤Next steps

请参阅此 ASP.NET Core 教程的 GitHub 存储库,了解有关详细信息,包括各种说明,即,如何向全新 ASP.NET Core Web 应用程序添加身份验证、如何调用 Microsoft Graph 和其他 Microsoft API、如何调用你自己的 API、如何添加授权、如何通过国家/地区云或社交标识等方式使用户登录:Check out the GitHub repo for this ASP.NET Core tutorial for more information including instructions on how to add authentication to a brand new ASP.NET Core Web application, how to call Microsoft Graph, and other Microsoft APIs, how to call your own APIs, how to add authorization, how to sign in users in national clouds, or with social identities and more: