调用 Web API 的守护程序应用 - 代码配置

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

支持守护程序应用的 Microsoft 库

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

语言/框架 项目
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
Java MSAL4J msal4j Library cannot request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
节点 MSAL Node msal-node 快速入门 Library cannot request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA
Python MSAL Python msal-python 快速入门 Library cannot request ID tokens for user sign-in. Library can request access tokens for protected web APIs. GA

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

配置颁发机构

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

在应用程序配置中指定的颁发机构应该是租户的(指定租户 ID 或者与组织相关联的域名)。

即使是需要提供多租户工具,也应在此流中使用租户 ID 或域名,而不是 commonorganizations,原因是该服务无法可靠推断出应使用哪个租户。

配置并实例化应用程序

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

重要

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

配置文件

配置文件定义:

  • 云实例和租户 ID,它们共同构成了“机构”。
  • 通过应用程序注册获得的客户端 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;

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

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

   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 读取配置:

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

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

代码本身完全一样。 配置中介绍了证书。 获取证书有多种方式。 有关详细信息,请参阅 https://aka.ms/ms-id-web-certificates。 下面介绍了如何从 KeyVault 获取证书。 Microsoft 标识委托给 Azure 标识的 DefaultAzureCredential,并使用了托管标识(如果可用)从 KeyVault 访问证书。 可在本地调试应用程序,因为它届时会使用开发人员凭据。

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

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

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

后续步骤

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