快速入门:用于让 Microsoft Entra 用户登录的 ASP.NET Web 应用

欢迎使用! 这可能不是你期望看到的页面。 在修复时,此链接应会将你转至正确的文章:

快速入门:向 ASP.NET Web 应用添加 Microsoft 登录功能

对此造成你的不便,我们深表歉意;感谢你的耐心等待,我们正在努力解决此问题。

在本快速入门中,你将下载并运行一个代码示例,该示例演示 ASP.NET Web 应用程序如何使用 Microsoft Entra 帐户让用户登录。

步骤 1:在 Azure 门户中配置应用程序

为使此快速入门中的代码示例正常运行,请为“重定向 URI”输入 https://localhost:44368/

已配置应用程序已使用此属性进行配置。

步骤 2:下载项目

使用 Visual Studio 2019 运行项目。

提示

若要避免由于 Windows 中路径长度限制导致的错误,我们建议将存档提取或克隆到驱动器根目录附近的目录中。

步骤 3:应用已配置并可以运行

我们已经为项目配置了应用属性的值。

  1. 将 .zip 文件解压缩到根文件夹附近的本地文件夹中。 例如,解压到 C:\Azure-Samples。

    建议将存档解压到驱动器根附近的目录中,以避免在 Windows 上出现路径长度限制导致的错误。

  2. 在 Visual Studio 中打开解决方案 (AppModelv2-WebApp-OpenIDConnect-DotNet.sln)。

  3. 可能需要右键单击项目“AppModelv2-WebApp-OpenIDConnect-DotNet”,然后选择“还原 NuGet 包”,具体取决于 Visual Studio 的版本 。

  4. 通过选择“查看”>“其他 Windows”>“包管理器控制台”,打开包管理器控制台 。 然后运行 Update-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform -r

注意

Enter_the_Supported_Account_Info_Here

详细信息

本部分概述了使用户登录所需的代码。 此概述对于了解代码的工作原理、主要参数是什么,以及如何向现有 ASP.NET 应用程序添加登录非常有用。

示例工作原理

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

OWIN 中间件 NuGet 包

可以将 ASP.NET 中的 OpenID Connect 与 OWIN 中间件包配合使用,通过基于 Cookie 的身份验证设置身份验证管道。 可在 Visual Studio 的包管理器控制台中运行以下命令,以便安装这些包:

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

OWIN 启动类

OWIN 中间件使用在托管进程初始化时运行的“启动类”。 在本快速入门中,startup.cs 文件位于根文件夹下。 以下代码显示本快速入门使用的参数:

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

    app.UseCookieAuthentication(new CookieAuthenticationOptions());
    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Sets the client ID, authority, and redirect URI 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's using the home page
            PostLogoutRedirectUri = redirectUri,
            Scope = OpenIdConnectScope.OpenIdProfile,
            // ResponseType is set to request the code id_token, which contains basic information about the signed-in user
            ResponseType = OpenIdConnectResponseType.CodeIdToken,
            // ValidateIssuer set to false to allow work accounts from any organization to sign in to your application
            // To only allow users from a single organization, set ValidateIssuer to true and the '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 the ValidIssuers parameter
            TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = false // Simplification (see note below)
            },
            // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to > the OnAuthenticationFailed method
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                AuthenticationFailed = OnAuthenticationFailed
            }
        }
    );
}
Where 说明
ClientId Azure 门户中注册的应用程序的应用程序 ID。
Authority 用户进行身份验证时使用的安全令牌服务 (STS) 终结点。 对于公共云,通常为 https://login.partner.microsoftonline.cn/{tenant}/v2.0。 在该 URL 中,{tenant} 是租户名称、租户 ID,或 common 是对常用终结点的引用。 (常用终结点用于多租户应用程序。)
RedirectUri 一个 URL,在通过 Microsoft 标识平台进行身份验证之后,会将用户发送到此 URL。
PostLogoutRedirectUri 一个 URL,在注销以后,会将用户发送到此 URL。
Scope 请求的作用域的列表,使用空格进行分隔。
ResponseType 来自身份验证响应的请求包含授权代码和 ID 令牌。
TokenValidationParameters 用于令牌验证的参数列表。 在这种情况下,ValidateIssuer 设置为 false,以指示它可以接受来自任何工作或学校帐户类型的登录。
Notifications 可以在 OpenIdConnect 消息上运行的委托的列表。

注意

在本快速入门中,设置 ValidateIssuer = false 是一种简化操作。 在实际应用程序中验证颁发者。 查看示例,了解如何执行该操作。

身份验证质询

可以通过在控制器中请求身份验证质询,强制用户登录:

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

提示

使用此方法请求身份验证质询是可选的。 如果希望已经身份验证和未经身份验证用户都可以访问视图,通常会使用此方法。 或者,可以使用下一节中所述的方法来保护控制器。

用于保护控制器或控制器操作的属性

可以使用 [Authorize] 属性保护控制器或控制器操作。 此属性通过仅允许经过身份验证的用户访问控制器中的操作来限制对控制器或操作的访问。 当未经身份验证的用户尝试访问由 [Authorize] 属性修饰的某个操作或控制器时,将自动发生身份验证质询。

帮助和支持

如果需要帮助、需要报告问题,或者需要详细了解支持选项,请参阅面向开发人员的帮助和支持

后续步骤

试用 ASP.NET 教程,了解有关构建应用程序和新功能的完整分步指南,包括本快速入门的完整说明。