

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# `GetClientToken`搭配使用 Amazon SDK
<a name="cognito-identity-provider_example_cognito-identity-provider_GetClientToken_section"></a>

以下代码示例演示了如何使用 `GetClientToken`。

操作示例是大型程序的代码摘录，必须在上下文中运行。在以下代码示例中，您可以查看此操作的上下文：
+  [客户令牌和条款发现](cognito-identity-provider_example_cognito-identity-provider_Scenario_ClientTokenAndTerms_section.md) 

------
#### [ Python ]

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [Amazon 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/cognito/scenarios/client_token#code-examples)中查找完整示例，了解如何进行设置和运行。

```
    def get_client_token(
        self,
        client_id: str,
        client_secret: str,
        scopes: Optional[list[str]] = None,
    ) -> dict[str, Any]:
        """
        Obtains an M2M access token for an app client using its client ID
        and secret, without end-user sign-in.

        :param client_id: The ID of the app client.
        :param client_secret: The client secret for the app client.
        :param scopes: Optional list of scopes in the format
                       'resource-server-identifier/scope-name'. If omitted,
                       all scopes configured for the app client are authorized.
        :return: A dictionary containing the ClientAuthenticationResult with
                 AccessToken, ExpiresIn, and TokenType.
        """
        try:
            params = dict()
            params["ClientId"] = client_id
            params["Secret"] = client_secret
            if scopes is not None:
                params["Scopes"] = scopes

            response = self.cognito_idp_client.get_client_token(**params)
            auth_result = response.get("ClientAuthenticationResult", dict())
            logger.info(
                "Obtained M2M access token for client %s. Token type: %s, expires in: %s seconds.",
                client_id,
                auth_result.get("TokenType", "Unknown"),
                auth_result.get("ExpiresIn", 0),
            )
            return auth_result
        except ClientError as err:
            if err.response["Error"]["Code"] == "NotAuthorizedException":
                logger.error(
                    "Not authorized for client %s. Verify that the client ID and "
                    "secret are correct, and that the ALLOW_CLIENT_TOKEN_AUTH flow "
                    "is enabled for the app client.",
                    client_id,
                )
            raise
```
+  有关 API 的详细信息，请参阅适用[GetClientToken](https://docs.amazonaws.cn/goto/boto3/cognito-idp-2016-04-18/GetClientToken)于 *Python 的Amazon SDK (Boto3) API 参考*。

------

有关 S Amazon DK 开发者指南和代码示例的完整列表，请参阅[将此服务与 Amazon SDK](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。