快速入门:向 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 use a code sample to learn how an ASP.NET web app to 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 new Azure portal - App registrations pane.
  2. 输入应用程序的名称,然后单击“注册”。Enter a name for your application and click 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 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:
    • 在“名称”部分输入一个会显示给应用用户的有意义的应用程序名称,例如 ASPNET-QuickstartIn the Name section, enter a meaningful application name that will be displayed to users of the app, for example ASPNET-Quickstart.
    • 在“重定向 URI”中添加 https://localhost:44368/,然后单击“注册”。Add https://localhost:44368/ in Redirect URI, and click Register.
    • 在“管理”部分下的左侧导航窗格中,选择“身份验证”From the left navigation pane under the Manage section, select Authentication
      • 在“隐式授权”子部分下,选择“ID 令牌”。Under the Implicit Grant sub-section, select ID tokens.
      • 然后选择“保存”。And then select Save.

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

要使此快速入门中的代码示例正常运行,需要将答复 URL 添加为 https://localhost:44368/For the code sample for this quickstart to work, you need to add a reply URL as 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 Microsoft identity platform endpoint
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 you need to 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.

后续步骤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.

了解创建本快速入门中使用的应用程序的步骤Learn the steps to create the application used in this quickstart

帮助和支持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.