快速入门:向 ASP.NET Web 应用添加 Microsoft 标识平台登录功能Quickstart: Add Microsoft identity platform sign-in to an ASP.NET web app

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

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

先决条件Prerequisites

注册并下载快速入门应用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 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. 输入应用程序的名称(例如 ASPNET-Quickstart)。Enter a Name for your application, for example ASPNET-Quickstart. 应用的用户可能会看到此名称,你稍后可对其进行更改。Users of your app might see this name, and you can change it later.
  6. 在“重定向 URI”中添加 https://localhost:44368/,然后选择“注册” 。Add https://localhost:44368/ in Redirect URI, and select Register.
  7. 在“管理”下,选择“身份验证”。 Under Manage, select Authentication.
  8. 在“隐式授权和混合流”部分,选择“ID 令牌” 。In the Implicit grant and hybrid flows section, select ID tokens.
  9. 选择“保存”。Select Save.

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

为使此快速入门中的代码示例正常运行,请添加重定向 URI https://localhost:44368/For the code sample in this quickstart to work, add a Redirect URI of https://localhost:44368/.

已配置 应用程序已使用此属性进行配置Already configured Your application is configured with this attribute

步骤 2:下载项目Step 2: Download your project

使用 Visual Studio 2019 运行项目。Run the project using Visual Studio 2019.

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

我们已经为项目配置了应用属性的值。We have configured your project with values of your app's properties.

步骤 3:运行 Visual Studio 项目Step 3: Run your Visual Studio project

  1. 将 zip 文件提取到更靠近根文件夹的本地文件夹(例如,C:\Azure-SamplesExtract the zip file to a local folder closer to the root folder - for example, C:\Azure-Samples
  2. 在 Visual Studio 中打开解决方案 (AppModelv2-WebApp-OpenIDConnect-DotNet.sln)Open the solution in Visual Studio (AppModelv2-WebApp-OpenIDConnect-DotNet.sln)
  3. 可能需要右键单击项目 AppModelv2-WebApp-OpenIDConnect-DotNet 和“还原 NuGet 包”,具体取决于 Visual Studio 的版本Depending on the version of Visual Studio, you might need to right click on the project AppModelv2-WebApp-OpenIDConnect-DotNet and Restore NuGet packages
  4. 打开包管理器控制台(“视图”->“其他 Windows”->“包管理器控制台”)并运行 Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -rOpen the Package Manager Console (View -> Other Windows -> Package Manager Console) and run Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r
  1. 编辑 Web.config,将参数 ClientIdTenant 替换为:Edit Web.config and replace the parameters ClientId and Tenant with:
    <add key="ClientId" value="Enter_the_Application_Id_here" />
    <add key="Tenant" value="Enter_the_Tenant_Info_Here" />
    
    其中:Where:
  • Enter_the_Application_Id_here - 是已注册应用程序的应用程序 ID。Enter_the_Application_Id_here - is the Application Id for the application you registered.
  • Enter_the_Tenant_Info_Here - 是下述选项之一:Enter_the_Tenant_Info_Here - is one of the options below:
    • 如果应用程序支持“仅我的组织”,请将该值替换为 租户 ID租户名称(例如 contoso.partner.onmschina.cn)If your application supports My organization only, replace this value with the Tenant Id or Tenant name (for example, contoso.partner.onmschina.cn)
    • 如果应用程序支持“任何组织目录中的帐户”,请将该值替换为organizationsIf your application supports Accounts in any organizational directory, replace this value with organizations

提示

  • 若要查找“应用程序 ID”、“目录(租户) ID”和“支持的帐户类型”的值,请转到“概览”页。 To find the values of Application ID, Directory (tenant) ID, and Supported account types, go to the Overview page
  • 确保 Web.configredirectUri 的值与 Azure AD 中为应用注册定义的 重定向 URI 相对应(如果不对应,请导航到应用注册的“身份验证”菜单,并更新 重定向 URI 以匹配)Ensure the value for redirectUri in the Web.config corresponds with the Redirect URI defined for the App Registration in Azure AD (if not, navigate to the Authentication menu for the App Registration and update the REDIRECT URI to match)

备注

Enter_the_Supported_Account_Info_Here

详细信息More information

本部分概述了登录用户所需的代码。This section gives an overview of the code required to sign-in users. 阅读本概述对于了解代码的工作原理、主要参数非常有用,如果你想要将登录功能添加到现有 ASP.NET 应用程序,阅读本概述也非常有用。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 application.

示例工作原理How the sample works

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

OWIN 中间件 NuGet 包OWIN middleware NuGet packages

可以将 ASP.NET 中的 OpenID Connect 与 OWIN 中间件包配合使用,通过基于 Cookie 的身份验证设置身份验证管道。You can set up the authentication pipeline with cookie-based authentication using OpenID Connect in ASP.NET with OWIN Middleware packages. 可在 Visual Studio 的 包管理器控制台 中运行以下命令,以便安装这些包:You can install these packages by running the following commands in Visual Studio's Package Manager Console:

Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb

OWIN 启动类OWIN Startup Class

OWIN 中间件使用在托管进程初始化时运行的“启动类”。The OWIN middleware uses a startup class that runs when the hosting process initializes. 在本快速入门中,startup.cs 文件位于根文件夹下。In this quickstart, the startup.cs file located in root folder. 以下代码显示本快速入门使用的参数:The following code shows the parameter used by this quickstart:

public void Configuration(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Sets the ClientId, authority, RedirectUri as obtained from web.config
            ClientId = clientId,
            Authority = authority,
            RedirectUri = redirectUri,
            // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
            PostLogoutRedirectUri = redirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the id_token - which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.IdToken,
            // ValidateIssuer set to false to allow work accounts from any organization to sign in to your application
            // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
            // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = false // Simplification (see note below)
            },
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed
            }
        }
    );
}
WhereWhere 说明Description
ClientId Azure 门户中注册的应用程序的应用程序 IDApplication ID from the application registered in the Azure portal
Authority 用户要进行身份验证的 STS 终结点。The STS endpoint for user to authenticate. 对于公有云,通常为 https://login.partner.microsoftonline.cn/{tenant}/v2.0,其中 {tenant} 是租户名称、租户 ID 或者引用常用终结点(用于多租户应用程序)的 commonUsually https://login.partner.microsoftonline.cn/{tenant}/v2.0 for public cloud, where {tenant} is the name of your tenant, your tenant Id, or common for a reference to the common endpoint (used for multi-tenant applications)
RedirectUri 一个 URL,在通过 Microsoft 标识平台进行身份验证之后,会将用户发送到此 URLURL where users are sent after authentication against the Microsoft identity platform
PostLogoutRedirectUri 一个 URL,在注销以后,会将用户发送到此 URLURL where users are sent after signing-off
Scope 请求的作用域的列表,使用空格进行分隔The list of scopes being requested, separated by spaces
ResponseType 请求身份验证的响应包含 ID 令牌Request that the response from authentication contains an ID token
TokenValidationParameters 用于令牌验证的参数列表。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 account types
Notifications 委托的列表,这些委托可以在不同的 OpenIdConnect 消息上执行A list of delegates that can be executed on different OpenIdConnect messages

备注

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

启动身份验证质询Initiate an authentication challenge

可以通过在控制器中请求身份验证质询,强制用户登录:You can force a user to sign in by requesting an authentication challenge in your controller:

public void SignIn()
{
    if (!Request.IsAuthenticated)
    {
        HttpContext.GetOwinContext().Authentication.Challenge(
            new AuthenticationProperties{ RedirectUri = "/" },
            OpenIdConnectAuthenticationDefaults.AuthenticationType);
    }
}

提示

如果希望视图可供经身份验证用户和未经身份验证用户访问,使用上述方法请求身份验证质询是可选的,也是常用的。Requesting an authentication challenge using the method above is optional and normally used when you want a view to be accessible from both authenticated and non-authenticated users. 或者,可以使用下一节中所述的方法来保护控制器。Alternatively, you can protect controllers by using the method described in the next section.

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

可以使用 [Authorize] 属性保护控制器或控制器操作。You can protect a controller or controller actions using the [Authorize] attribute. 此属性限制对控制器或操作的访问,其方法是仅允许经身份验证的用户访问控制器中的操作。这意味着,当未经身份验证的用户尝试访问 [Authorize] 属性修饰的某个操作或控制器时,会自动进行身份验证质询。This attribute restricts access to the controller or actions by allowing only authenticated users to access the actions in the controller, which means that authentication challenge will happen automatically when a non-authenticated user tries to access one of the actions or controller decorated by the [Authorize] attribute.

帮助和支持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 教程,了解有关构建应用程序和新功能的完整分步指南,包括本快速入门的完整说明。Try out the ASP.NET tutorial for a complete step-by-step guide on building applications and new features, including a full explanation of this quickstart.