获取令牌以使用守护程序应用程序调用 Web API

在构建机密客户端应用程序以后,可以获取应用的令牌,方法是调用 AcquireTokenForClient,传递作用域,然后强制刷新令牌。

请求的作用域

请求客户端凭据流时,其作用域是资源的名称后跟 /.default。 这种表示法告知 Microsoft Entra ID 使用在应用程序注册过程中静态声明的应用程序级权限。 另外,这些 API 权限必须由租户管理员授予。

在 MSAL Python 中,该配置文件应该如以下代码片段所示:

{
    "scope": ["https://microsoftgraph.chinacloudapi.cn/.default"],
}

Azure AD (v1.0) 资源

用于客户端凭据的作用域应该始终为资源 ID 后跟 /.default

重要

当 MSAL 为接受 1.0 版访问令牌的资源请求访问令牌时,Microsoft Entra ID 会获取最后一个斜杠前面的所有内容并将其用作资源标识符,从请求的范围内分析所需的受众。 因此,就像 Azure SQL 数据库 (https://database.chinacloudapi.cn) 一样,如果资源需要以斜杠结尾的受众(对于 Azure SQL 数据库为 https://database.chinacloudapi.cn/),你将需要请求作用域 https://database.chinacloudapi.cn//.default。 (注意双斜杠。)另请参阅 MSAL.NET 问题 #747:Resource url's trailing slash is omitted, which caused sql auth failure

AcquireTokenForClient API

为了获取应用的令牌,请使用 AcquireTokenForClient 或其等效命令,具体取决于平台。

# The pattern to acquire a token looks like this.
result = None

# First, the code looks up a token from the cache.
# Because we're looking for a token for the current app, not for a user,
# use None for the account parameter.
result = app.acquire_token_silent(config["scope"], account=None)

if not result:
    logging.info("No suitable token exists in cache. Let's get a new one from Azure AD.")
    result = app.acquire_token_for_client(scopes=config["scope"])

if "access_token" in result:
    # Call a protected API with the access token.
    print(result["token_type"])
else:
    print(result.get("error"))
    print(result.get("error_description"))
    print(result.get("correlation_id"))  # You might need this when reporting a bug.

协议

如果还没有适用于所选语言的库,你可能希望直接使用协议:

第一种情况:使用共享机密访问令牌请求

POST /{tenant}/oauth2/v2.0/token HTTP/1.1           //Line breaks for clarity.
Host: login.partner.microsoftonline.cn
Content-Type: application/x-www-form-urlencoded

client_id=00001111-aaaa-2222-bbbb-3333cccc4444
&scope=https%3A%2F%2Fmicrosoftgraph.chinacloudapi.cn%2F.default
&client_secret=A1b-C2d_E3f.H4i,J5k?L6m!N7o-P8q_R9s.T0u
&grant_type=client_credentials

第二种情况:使用证书访问令牌请求

POST /{tenant}/oauth2/v2.0/token HTTP/1.1               // Line breaks for clarity.
Host: login.partner.microsoftonline.cn
Content-Type: application/x-www-form-urlencoded

scope=https%3A%2F%2Fmicrosoftgraph.chinacloudapi.cn%2F.default
&client_id=11112222-bbbb-3333-cccc-4444dddd5555
&client_assertion_type=urn%3Aietf%3Aparams%3Aoauth%3Aclient-assertion-type%3Ajwt-bearer
&client_assertion=aaaaaaaa-0b0b-...
&grant_type=client_credentials

有关详细信息,请参阅协议文档:Microsoft 标识平台和 OAuth 2.0 客户端凭据流

故障排除

你是否使用过 resource/.default 作用域?

如果出现一条错误消息,指出所使用的作用域无效,则表明你并未使用 resource/.default 作用域。

如果在调用 API 时出现错误“权限不足,无法完成该操作”, 则租户管理员需要授予对应用程序的权限。

如果未向应用程序授予管理员同意,将遇到以下错误:

Failed to call the web API: Forbidden
Content: {
  "error": {
    "code": "Authorization_RequestDenied",
    "message": "Insufficient privileges to complete the operation.",
    "innerError": {
      "request-id": "<guid>",
      "date": "<date>"
    }
  }
}

根据角色选择以下选项之一。

云应用程序管理员

对于云应用程序管理员,请转到 Microsoft Entra 管理中心中的“企业应用程序”。 选择应用注册,然后从左侧窗格的“安全”部分中选择“权限”。 然后,选择标有“为 {租户名称} 授予管理员同意”的大按钮,(其中 {租户名称} 是你的目录的名称)。

标准用户

对于租户的标准用户,可以请求云应用程序管理员为应用程序授予管理员同意。 为此,请为管理员提供以下 URL:

https://login.partner.microsoftonline.cn/Enter_the_Tenant_Id_Here/adminconsent?client_id=Enter_the_Application_Id_Here

在 URL 中:

  • Enter_the_Tenant_Id_Here 替换为租户 ID 或租户名称(例如,contoso.microsoft.com)。
  • Enter_the_Application_Id_Here 是已注册的应用程序的应用程序(客户端)ID。

在使用上述 URL 为应用授予同意后,可能会显示错误 AADSTS50011: No reply address is registered for the application。 之所以出现此错误,是因为此应用程序和 URL 没有重定向 URI。 这可予以忽视。

是否在调用自己的 API?

如果你的守护程序应用调用你自己的 Web API,并且你无法向守护程序的应用注册添加应用权限,则需要将应用角色添加到 Web API 的应用注册

后续步骤

转到此方案中的下一篇文章:调用 Web API