调用 Web API 的守护程序应用 - 代码配置Daemon app that calls web APIs - code configuration

了解如何为调用 Web API 的守护程序应用程序配置代码。Learn how to configure the code for your daemon application that calls web APIs.

支持守护程序应用的 MSAL 库MSAL libraries that support daemon apps

以下 Microsoft 库支持守护程序应用:These Microsoft libraries support daemon apps:

MSAL 库MSAL library 说明Description
MSAL.NET
MSAL.NETMSAL.NET
支持使用 .NET Framework 和 .NET Core 平台构建守护程序应用程序。The .NET Framework and .NET Core platforms are supported for building daemon applications. (不支持 UWP、Xamarin.iOS 和 Xamarin.Android,因为这些平台用于生成公共客户端应用程序。)(UWP, Xamarin.iOS, and Xamarin.Android aren't supported because those platforms are used to build public client applications.)
Python
MSAL PythonMSAL Python
Python 中支持守护程序应用程序。Support for daemon applications in Python.
Java
MSAL JavaMSAL Java
Java 中支持守护程序应用程序。Support for daemon applications in Java.

配置颁发机构Configure the authority

守护程序应用程序使用应用程序权限,而不是委托的权限。Daemon applications use application permissions rather than delegated permissions. 因此,它们支持的帐户类型不能是任何组织目录中的帐户。So their supported account type can't be an account in any organizational directory. 你需要选择“我的组织中的帐户” 或“任何组织中的帐户” 。You'll need to choose accounts in my organization or accounts in any organization.

因此,在应用程序配置中指定的颁发机构应该是租户的(指定租户 ID 或者与组织相关联的域名)。So the authority specified in the application configuration should be tenanted (specifying a tenant ID or a domain name associated with your organization).

如果你是 ISV 并且希望提供多租户工具,则可以使用 organizationsIf you're an ISV and want to provide a multitenant tool, you can use organizations. 但请记住,你还需向客户说明如何授予管理员同意。But keep in mind that you'll also need to explain to your customers how to grant admin consent. 有关详细信息,请参阅请求整个租户的许可For details, see Requesting consent for an entire tenant. 此外,目前 MSAL 中有一个限制:仅当客户端凭据是应用程序机密(而不是证书)时才允许使用 organizationsAlso, there's currently a limitation in MSAL: organizations is allowed only when the client credentials are an application secret (not a certificate).

配置并实例化应用程序Configure and instantiate the application

在 MSAL 库中,客户端凭据(机密或证书)是作为机密客户端应用程序构造的参数传递的。In MSAL libraries, the client credentials (secret or certificate) are passed as a parameter of the confidential client application construction.

重要

即使应用程序是作为服务运行的控制台应用程序,如果它是守护程序应用程序,则也需要是机密客户端应用程序。Even if your application is a console application that runs as a service, if it's a daemon application, it needs to be a confidential client application.

配置文件Configuration file

配置文件定义:The configuration file defines:

  • 颁发机构或者云实例和租户 ID。The authority or the cloud instance and tenant ID.
  • 通过应用程序注册获得的客户端 ID。The client ID that you got from the application registration.
  • 客户端机密或证书。Either a client secret or a certificate.

备注

本文其余部分中的 .Net 代码片段引用了 active-directory-dotnetcore-daemon-v2 示例中的 configThe .Net code snippets in the rest of the article reference config from the active-directory-dotnetcore-daemon-v2 sample.

appsettings.json,来自 .NET Core 控制台守护程序示例。appsettings.json from the .NET Core console daemon sample.

{
  "Instance": "https://login.partner.microsoftonline.cn/{0}",
  "Tenant": "[Enter here the tenantID or domain name for your Azure AD tenant]",
  "ClientId": "[Enter here the ClientId for your application]",
  "ClientSecret": "[Enter here a client secret for your application]",
  "CertificateName": "[Or instead of client secret: Enter here the name of a certificate (from the user cert store) as registered with your application]"
}

请提供 ClientSecretCertificateNameYou provide either a ClientSecret or a CertificateName. 这些设置是互斥的。These settings are exclusive.

实例化 MSAL 应用程序Instantiate the MSAL application

若要实例化 MSAL 应用程序,你需要添加、引用或导入 MSAL 包(取决于语言)。To instantiate the MSAL application, you need to add, reference, or import the MSAL package (depending on the language).

构造取决于你是使用客户端机密还是使用证书(还是使用已签名断言,这是一种高级方案)。The construction is different, depending on whether you're using client secrets or certificates (or, as an advanced scenario, signed assertions).

引用此包Reference the package

在应用程序代码中引用 MSAL 包。Reference the MSAL package in your application code.

向应用程序添加 Microsoft.IdentityClient NuGet 包。Add the Microsoft.IdentityClient NuGet package to your application. 在 MSAL.NET 中,机密客户端应用程序通过 IConfidentialClientApplication 接口表示。In MSAL.NET, the confidential client application is represented by the IConfidentialClientApplication interface. 在源代码中使用 MSAL.NET 命名空间。Use the MSAL.NET namespace in the source code.

using Microsoft.Identity.Client;
IConfidentialClientApplication app;

使用客户端机密实例化机密客户端应用程序Instantiate the confidential client application with a client secret

下面的代码用于使用客户端机密实例化机密客户端应用程序:Here's the code to instantiate the confidential client application with a client secret:

app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
           .WithClientSecret(config.ClientSecret)
           .WithAuthority(new Uri(config.Authority))
           .Build();

通过客户端证书实例化机密客户端应用程序Instantiate the confidential client application with a client certificate

下面的代码用于使用证书来构建应用程序:Here's the code to build an application with a certificate:

X509Certificate2 certificate = ReadCertificate(config.CertificateName);
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
    .WithCertificate(certificate)
    .WithAuthority(new Uri(config.Authority))
    .Build();

高级方案:使用客户端断言实例化机密客户端应用程序Advanced scenario: Instantiate the confidential client application with client assertions

机密客户端应用程序还可以使用客户端断言(而不是客户端密码或证书)来证明其身份。Instead of a client secret or a certificate, the confidential client application can also prove its identity by using client assertions.

MSAL.NET 可以通过两种方法将签名的断言提供给机密客户端应用:MSAL.NET has two methods to provide signed assertions to the confidential client app:

  • .WithClientAssertion()
  • .WithClientClaims()

使用 WithClientAssertion 时,需提供签名的 JWT。When you use WithClientAssertion, you need to provide a signed JWT. 客户端断言详细介绍了这一高级方案。This advanced scenario is detailed in Client assertions.

string signedClientAssertion = ComputeAssertion();
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                                          .WithClientAssertion(signedClientAssertion)
                                          .Build();

使用 WithClientClaims 时,MSAL.NET 将生成一个已签名断言,其中包含 Azure AD 预期的声明,以及你想要发送的其他客户端声明。When you use WithClientClaims, MSAL.NET will produce a signed assertion that contains the claims expected by Azure AD, plus additional client claims that you want to send. 此代码展示了如何执行该操作:This code shows how to do that:

string ipAddress = "192.168.1.2";
var claims = new Dictionary<string, string> { { "client_ip", ipAddress } };
X509Certificate2 certificate = ReadCertificate(config.CertificateName);
app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
                                          .WithAuthority(new Uri(config.Authority))
                                          .WithClientClaims(certificate, claims)
                                          .Build();

同样,如需详细信息,请参阅客户端断言Again, for details, see Client assertions.

后续步骤Next steps