可将用户登录的 Web 应用:代码配置

了解如何为可将用户登录的 Web 应用配置代码。

支持 Web 应用的 Microsoft 库

以下 Microsoft 库用于保护 Web 应用(和 Web API):

语言/框架 项目
GitHub
获取
started
用户登录 访问 Web API 正式发布 (GA) 或
公共预览版1
.NET MSAL.NET Microsoft.Identity.Client Library cannot request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
.NET Microsoft.IdentityModel Microsoft.IdentityModel Library cannot request ID tokens for user sign-in.2 Library cannot request access tokens for protected web APIs.2 GA
ASP.NET Core ASP.NET Core Microsoft.AspNetCore.Authentication 快速入门 Library can request ID tokens for user sign-in. Library cannot request access tokens for protected web APIs. GA
ASP.NET Core Microsoft.Identity.Web Microsoft.Identity.Web 快速入门 Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
Java MSAL4J msal4j 快速入门 Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
Spring spring-cloud-azure-starter-active-directory spring-cloud-azure-starter-active-directory 教程 Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
Node.js MSAL Node msal-node 快速入门 Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
Python MSAL Python msal Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
Python identity identity 快速入门 Library can request ID tokens for user sign-in. Library can request access tokens for protected web APIs. --

(1)在线服务通用许可条款适用于公共预览版中的库。

(2)Microsoft.IdentityModel 库仅验证令牌,它不能请求 ID 或访问令牌。

选择与所需平台对应的选项卡:

本文中的代码片段及以下内容摘自 ASP.NET Core Web 应用增量教程第 1 章

你可能需要参考该教程来了解完整的实现细节。

配置文件

使用 Microsoft 标识平台将用户登录的 Web 应用程序是通过配置文件配置的。 这些文件必须指定以下值:

  • 实例(例如,如果需要在国家云中运行应用)。 不同的选项包括:
    • https://login.partner.microsoftonline.cn/common:中国 Microsoft Entra(由世纪互联运营)
  • 租户 ID 中的受众。 选项根据应用是单租户还是多租户而异。
    • 从 Azure 门户获取的租户 GUID,用于将组织中的用户登录。 也可以使用域名。
    • organizations,让用户使用任何工作或学校帐户登录
    • common,让用户使用任何工作或学校帐户登录
  • 应用程序的客户端 ID,从 Azure 门户中复制

还可能会看到对颁发机构的引用、实例租户 ID 值的串联。

在 ASP.NET Core 中,这些设置位于 appsettings.json 文件的“Microsoft Entra ID”节中。

{
  "AzureAd": {
    "Instance": "https://login.partner.microsoftonline.cn/",
    "TenantId": "[Enter the tenantId here]",

    // Client ID (application ID) obtained from the Azure portal
    "ClientId": "[Enter the Client Id here]",
    "CallbackPath": "/signin-oidc",
    "SignedOutCallbackPath": "/signout-oidc"
  }
}

在 ASP.NET Core 中,另一个文件 (properties\launchSettings.json) 包含应用程序的 URL (applicationUrl) 和 TLS/SSL 端口 (sslPort),以及各种配置文件。

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:3110/",
      "sslPort": 44321
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "webApp": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:3110/"
    }
  }
}

在 Azure 门户中,在应用程序的“身份验证”页中注册的重定向 URI 需与这些 URL 相匹配。 对于上述两个配置文件,URL 为 https://localhost:44321/signin-oidc。 原因是 applicationUrlhttp://localhost:3110,但指定的是 sslPort (44321)。 CallbackPathappsettings.json 中定义的 /signin-oidc

注销 URI 将采用相同方式设置为 https://localhost:44321/signout-oidc

注意

SignedOutCallbackPath 应设置为门户或应用程序,以避免在处理事件时发生冲突。

初始化代码

初始化代码的差异与平台相关。 对于 ASP.NET Core 和 ASP.NET,用户登录将委托给 OpenID Connect 中间件来完成。 ASP.NET 或 ASP.NET Core 模板会为 Azure AD v1.0 终结点生成 Web 应用程序。 只需进行一些配置就能使这些应用程序适应 Microsoft 标识平台。

在 ASP.NET Core Web 应用(和 Web API)中,应用程序受到保护,因为控制器或控制器操作中包含 Authorize 属性。 此属性检查是否已对用户进行身份验证。 在 .NET 6 发布之前,代码初始化位于 Startup.cs 文件中。 使用 .NET 6 的新 ASP.NET Core 项目不再包含 Startup.cs 文件。 代替它的是 Program.cs 文件。 本教程的其余部分与 .NET 5 或更低版本相关。

注意

如果你想直接从 Microsoft 标识平台的利用 Microsoft.Identity.Web 的新 ASP.NET Core 模板开始,可以下载一个包含 .NET 5.0 项目模板的 NuGet 预览包。 然后,在安装后,可以直接实例化 ASP.NET Core Web 应用程序(MVC 或 Blazor)。 有关详细信息,请参阅 Microsoft.Identity.Web Web 应用项目模板。 这是最简单的方法,因为它将执行以下所有步骤。

如果你想使用 Visual Studio 中的当前默认 ASP.NET Core Web 项目来启动项目,或者使用 dotnet new mvc --auth SingleOrgdotnet new webapp --auth SingleOrg 来启动项目,则会看到如下所示的代码:

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

此代码使用旧版 Microsoft.AspNetCore.Authentication.AzureAD.UI NuGet 包,该包用于创建 Azure Active Directory v1.0 应用程序。 本文介绍如何创建一个用于替换该代码的 Microsoft 标识平台 v2.0 应用程序。

  1. Microsoft.Identity.WebMicrosoft.Identity.Web.UI NuGet 包添加到项目。 删除 Microsoft.AspNetCore.Authentication.AzureAD.UI NuGet 包(如果存在)。

  2. 更新 ConfigureServices 中的代码,使其使用 AddMicrosoftIdentityWebAppAddMicrosoftIdentityUI 方法。

    public class Startup
    {
     ...
     // This method gets called by the runtime. Use this method to add services to the container.
     public void ConfigureServices(IServiceCollection services)
     {
      services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
             .AddMicrosoftIdentityWebApp(Configuration, "AzureAd");
    
      services.AddRazorPages().AddMvcOptions(options =>
      {
       var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
       options.Filters.Add(new AuthorizeFilter(policy));
      }).AddMicrosoftIdentityUI();
    
  3. 在 Startup.cs 的 Configure 方法中,通过调用 app.UseAuthentication();app.MapControllers(); 启用身份验证。

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
     // more code here
     app.UseAuthentication();
     app.UseAuthorization();
    
     app.MapRazorPages();
     app.MapControllers();
     // more code here
    }
    

在该代码中:

  • AddMicrosoftIdentityWebApp 扩展方法在 Microsoft.Identity.Web 中定义,其中:

    • 配置用于读取配置文件的选项(此处来自“Microsoft Entra ID”节)
    • 配置 OpenID Connect 选项,将颁发机构设为 Microsoft 标识平台。
    • 验证令牌的颁发者。
    • 确保从 ID 令牌中的 preferred_username 声明映射与名称对应的声明。
  • 除了配置对象以外,还可以在调用 AddMicrosoftIdentityWebApp 时指定配置节的名称。 该名称默认为 AzureAd

  • AddMicrosoftIdentityWebApp 包含高级方案的其他参数。 例如,当身份验证不起作用时,跟踪 OpenID Connect 中间件事件有助于排查 Web 应用程序的问题。 将可选参数 subscribeToOpenIdConnectMiddlewareDiagnosticsEvents 设为 true 会显示 ASP.NET Core 中间件集在从 HTTP 响应进展到 HttpContext.User 中用户标识的过程中是如何处理信息的。

  • AddMicrosoftIdentityUI 扩展方法在 Microsoft.Identity.Web.UI 中进行定义。 它提供了一个默认控制器来处理登录和注销。

若要详细了解如何使用 Microsoft.Identity.Web 创建 Web 应用,请参阅 microsoft-identity-web 中的 Web 应用

后续步骤

下一篇文章将会介绍如何触发登录和注销。

转到此方案中的下一篇文章:登录和注销