如何配置调用 Web API 的守护程序应用

了解如何为调用 Web API 的守护程序应用程序配置代码。

支持守护程序应用的 Microsoft 库

以下 Microsoft 库支持守护程序应用:

语言/框架 项目开启
GitHub
软件包 获取
入门
用户登录 访问 Web API 正式发布 (GA)
公共预览版1
.NET MSAL.NET Microsoft.Identity.Client 快速入门 库无法为用户登录请求 ID令牌。 库可以为受保护的 Web API 请求访问令牌。 GA
Java MSAL4J msal4j 库无法为用户登录请求 ID令牌。 库可以为受保护的 Web API 请求访问令牌。 GA
Node MSAL 节点 msal-node 快速入门 库无法为用户登录请求 ID令牌。 库可以为受保护的 Web API 请求访问令牌。 GA
Python MSAL Python msal-python 快速入门 库无法为用户登录请求 ID令牌。 库可以为受保护的 Web API 请求访问令牌。 GA

1联机服务通用许可条款适用于公共预览版中的库。

配置证书颁发机构

守护程序应用程序使用应用程序权限,而不是委托的权限。 因此,它们支持的帐户类型不能是任何组织目录中的帐户。 你需要选择“我的组织中的帐户”或“任何组织中的帐户”。

应用程序配置中指定的颁发机构应包含你的租户 ID 或与你的组织关联的域名。

即使在需要提供多租户工具的情况下,也应在此流中使用租户 ID 或域名,而不是 common,因为该服务无法可靠推断应使用哪个租户。organizations

配置并实例化应用程序

在Microsoft身份验证库(MSAL)中,客户端凭据(机密或证书)作为机密客户端应用程序构造的参数传递。

重要

即使应用程序是作为服务运行的控制台应用程序,如果它是守护程序应用程序,则也需要是机密客户端应用程序。

配置文件

配置文件定义:

  • 云实例和租户 ID,二者共同构成 authority
  • 通过应用程序注册获得的客户端 ID。
  • 客户端机密或证书。

下面是在 appsettings.json 示例配置文件中定义配置的示例。 此示例摘自 GitHub 上的 .NET 控制台守护程序代码示例。

{
    "AzureAd": {
        "Instance": "https://login.partner.microsoftonline.cn/",
        "TenantId": "[Enter here the tenantID or domain name for your Azure AD tenant]",
        "ClientId": "[Enter here the ClientId for your application]",
        "ClientCredentials": [
            {
                "SourceType": "ClientSecret",
                "ClientSecret": "[Enter here a client secret for your application]"
            }
        ]
    }
}

请提供证书而不是客户端密码或工作负载联合身份验证凭据。

实例化 MSAL 应用程序

若要实例化 MSAL 应用程序,请添加、引用或导入 MSAL 包(取决于语言)。

其构造方式会有所不同,具体取决于你使用的是客户端密码还是证书(或者,在高级场景中,使用签名断言)。

引用此包

在应用程序代码中引用 MSAL 包。

向应用程序添加 Microsoft.Identity.Web.TokenAcquisition NuGet 包。 或者,如果要调用 Microsoft Graph,请添加 Microsoft.Identity.Web.GraphServiceClient 包。 你的项目可能如下所示。 需要将 appsettings.json 文件复制到输出目录。

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <RootNamespace>daemon_console</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.Identity.Web.GraphServiceClient" Version="2.12.2" />
  </ItemGroup>

  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
  </ItemGroup>
</Project>

在 Program.cs 文件中,在代码中添加 using 指令以引用 Microsoft.Identity.Web。

using Microsoft.Identity.Abstractions;
using Microsoft.Identity.Web;

使用客户端机密实例化机密客户端应用程序

以下是使用客户端密码实例化机密客户端应用程序的代码:

以下示例演示如何使用 Microsoft.Identity.Web 和客户端机密创建机密客户端应用程序:

   class Program
    {
        static async Task Main(string[] _)
        {
            // Get the Token acquirer factory instance. By default it reads an appsettings.json
            // file if it exists in the same folder as the app (make sure that the 
            // "Copy to Output Directory" property of the appsettings.json file is "Copy if newer").
            TokenAcquirerFactory tokenAcquirerFactory = TokenAcquirerFactory.GetDefaultInstance();

            // Configure the application options to be read from the configuration
            // and add the services you need (Graph, token cache)
            IServiceCollection services = tokenAcquirerFactory.Services;
            services.AddMicrosoftGraph();
            // By default, you get an in-memory token cache.
            // For more token cache serialization options, see https://aka.ms/msal-net-token-cache-serialization

            // Resolve the dependency injection.
            var serviceProvider = tokenAcquirerFactory.Build();

            // ...
        }
    }

配置从 appsettings.json 中读取:

通过客户端证书实例化机密客户端应用程序

下面的代码用于使用证书来构建应用程序:

应用程序构造代码与客户端机密示例相同。 唯一的区别在于,证书是在配置中描述的,而不是机密。 获取证书有多种方式。 有关详细信息,请参阅在 Microsoft Identity Web 中使用证书。 以下配置示例演示如何从Azure 密钥保管库检索证书。 Microsoft 标识库使用 Azure Identity 的 DefaultAzureCredential,并在可用时使用托管标识来访问 Key Vault 中的证书。 你可以在本地调试应用程序,因为此时 DefaultAzureCredential 会使用你的开发人员凭据。

  "ClientCredentials": [
      {
        "SourceType": "KeyVault",
        "KeyVaultUrl": "https://yourKeyVaultUrl.vault.azure.cn",
        "KeyVaultCertificateName": "NameOfYourCertificate"
      }

高级场景:使用客户端断言实例化机密客户端应用程序

除了使用客户端密码或证书,机密客户端应用程序还可以使用客户端断言来证明其身份。 请参阅 CredentialDescription 了解详细信息。

后续步骤

转到此方案中的下一篇文章:获取应用的令牌