调用 Web API 的守护程序应用 - 从应用调用 Web APIDaemon app that calls web APIs - call a web API from the app

.NET 守护程序应用可以调用一个 Web API。.NET daemon apps can call a web API. .NET 守护程序应用还可以调用多个预先批准的 Web API。.NET daemon apps can also call several pre-approved web APIs.

从守护程序应用程序调用一个 Web APICalling a web API from a daemon application

下面介绍如何使用令牌来调用一个 API:Here's how to use the token to call an API:

MSAL.NET 中的 AuthenticationResult 属性AuthenticationResult properties in MSAL.NET

用于获取令牌的方法返回 AuthenticationResultThe methods to acquire tokens return AuthenticationResult. 对于异步方法,将返回 Task<AuthenticationResult>For async methods, Task<AuthenticationResult> returns.

在 MSAL.NET 中,AuthenticationResult 会公开In MSAL.NET, AuthenticationResult exposes:

  • AccessToken,以便 Web API 访问资源。AccessToken for the web API to access resources. 此参数是一个字符串,通常是一个 Base-64 编码的 JWT。This parameter is a string, usually a Base-64-encoded JWT. 客户端不应该查看访问令牌的内部。The client should never look inside the access token. 不保证格式稳定,并且可以为资源加密令牌。The format isn't guaranteed to remain stable, and it can be encrypted for the resource. 编写的代码依赖于客户端上的访问令牌内容是最大的错误来源之一,并且会违反客户端逻辑。Writing code that depends on access token content on the client is one of the biggest sources of errors and client logic breaks. 有关详细信息,请参阅访问令牌For more information, see Access tokens.
  • 用户的 IdTokenIdToken for the user. 此参数是编码的 JWT。This parameter is an encoded JWT. 有关详细信息,请参阅 ID 令牌For more information, see ID tokens.
  • ExpiresOn 会告知令牌过期的日期和时间。ExpiresOn tells the date and time when the token expires.
  • TenantId 包含用户所在的租户。TenantId contains the tenant in which the user was found. 对于 Azure Active Directory (Azure AD) B2B 方案中的来宾用户,租户 ID 是来宾租户,而不是唯一的租户。For guest users in Azure Active Directory (Azure AD) B2B scenarios, the tenant ID is the guest tenant, not the unique tenant. 为用户传送令牌时,AuthenticationResult 还包含有关此用户的信息。When the token is delivered for a user, AuthenticationResult also contains information about this user. 对于在请求令牌时未提供应用用户的机密客户端流,此用户信息为 null。For confidential client flows where tokens are requested with no user for the application, this user information is null.
  • 令牌的颁发ScopesThe Scopes for which the token was issued.
  • 用户的唯一 ID。The unique ID for the user.

IAccountIAccount

MSAL.NET 通过 IAccount 接口定义了帐户的概念。MSAL.NET defines the notion of an account through the IAccount interface. 此中断性变更提供了正确的语义。This breaking change provides the right semantics. 同一用户可以在不同的 Azure AD 目录中拥有多个帐户。The same user can have several accounts, in different Azure AD directories. 此外,由于会提供主帐户信息,MSAL.NET 可以在使用来宾方案的情况下提供更有用的信息。Also, MSAL.NET provides better information in the case of guest scenarios because home account information is provided. 下图显示了 IAccount 接口的结构。The following diagram shows the structure of the IAccount interface.

IAccount 接口结构

AccountId 类使用下表中显示的属性标识特定租户中的帐户。The AccountId class identifies an account in a specific tenant with the properties shown in the following table.

属性Property 说明Description
TenantId GUID 的字符串表示形式,是帐户所在租户的 ID。A string representation for a GUID, which is the ID of the tenant where the account resides.
ObjectId GUID 的字符串表示形式,是拥有租户中的帐户的用户的 ID。A string representation for a GUID, which is the ID of the user who owns the account in the tenant.
Identifier 帐户的唯一标识符。Unique identifier for the account. IdentifierObjectIdTenantId 的串联,由逗号分隔。Identifier is the concatenation of ObjectId and TenantId separated by a comma. 它们不是 Base 64 编码的。They're not Base 64 encoded.

IAccount 接口表示单个帐户的相关信息。The IAccount interface represents information about a single account. 同一用户可以存在于不同的租户中,这意味着一个用户可以有多个帐户。The same user can be present in different tenants, which means that a user can have multiple accounts. 其成员显示在下表中。Its members are shown in the following table.

属性Property 说明Description
Username 一个字符串,包含 UserPrincipalName (UPN) 格式的可显示值,例如 john.doe@contoso.com。A string that contains the displayable value in UserPrincipalName (UPN) format, for example, john.doe@contoso.com. 此字符串可以为 null,这不同于 HomeAccountId 和 HomeAccountId.Identifier,后两者不会为 null。This string can be null, unlike HomeAccountId and HomeAccountId.Identifier, which won't be null. 此属性替换 MSAL.NET 旧版本中 IUserDisplayableId 属性。This property replaces the DisplayableId property of IUser in previous versions of MSAL.NET.
Environment 一个字符串,包含此帐户的标识提供者,例如 login.partner.microsoftonline.cnA string that contains the identity provider for this account, for example, login.partner.microsoftonline.cn. 此属性替换 IUserIdentityProvider 属性,不同之处是 IdentityProvider 还包含除云环境以外的租户信息。This property replaces the IdentityProvider property of IUser, except that IdentityProvider also had information about the tenant, in addition to the cloud environment. 而此处的该值仅仅是主机。Here, the value is only the host.
HomeAccountId 用户的主帐户的帐户 ID。The account ID of the home account for the user. 此属性唯一标识 Azure AD 租户的用户。This property uniquely identifies the user across Azure AD tenants.

使用令牌调用受保护的 APIUse the token to call a protected API

在 MSAL 在 result 中返回 AuthenticationResult 后,将它添加到 HTTP 授权标头,然后再调用该令牌以访问受保护的 Web API。After AuthenticationResult is returned by MSAL in result, add it to the HTTP authorization header before you make the call to access the protected web API.

httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);

// Call the web API.
HttpResponseMessage response = await _httpClient.GetAsync(apiUri);
...
}

调用多个 APICalling several APIs

对于守护程序应用,需要预先批准调用的 Web API。For daemon apps, the web APIs that you call need to be pre-approved. 守护程序应用没有增量同意。There's no incremental consent with daemon apps. (没有用户交互。)租户管理员需要预先为应用程序提供同意和所有 API 权限。(There's no user interaction.) The tenant admin needs to provide consent in advance for the application and all the API permissions. 如果要调用多个 API,则每次调用 AcquireTokenForClient 时都需要为每个资源获取一个令牌。If you want to call several APIs, you need to acquire a token for each resource, each time calling AcquireTokenForClient. MSAL 将使用应用程序令牌缓存来避免不必要的服务调用。MSAL will use the application token cache to avoid unnecessary service calls.

后续步骤Next steps