

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

# 示例：对 AgentCore CLI 创建的默认网关和目标的授权
<a name="gateway-using-auth-ex-starter"></a>

如果您使用 AgentCore CLI 创建网关和 Lambda 目标，CLI 会自动为您配置 JWT-based 入站授权和 IAM-based 出站授权。

**注意**  
如果您使用调用网关`agentcore invoke`，CLI 会自动处理身份验证。仅当您想以编程方式调用网关（例如，使用 Amazon SDK 或`curl`）时，才需要执行以下步骤。

要进行编程访问，您将通过以下方式进行授权：
+  **使用 JWT 进行入站授权 ** — 从自动为您设置的 Amazon Cognito 授权中获取访问令牌，并将其包含在授权标题中。请参阅以下示例，了解如何获取代币。
+  **使用 IAM 进行出站授权 ** — AgentCore CLI 为您配置以下权限，因此您无需进行任何额外设置：
  + 您的网关服务角色有权调用 Lambda 中的所有函数（由[BedrockAgentCoreFullAccess](https://docs.amazonaws.cn/aws-managed-policy/latest/reference/BedrockAgentCoreFullAccess.html)托管策略提供）。
  + 创建的 Lambda 函数使用您的网关服务角色配置为可以调用`Principal`该函数。

您可以通过收集以下信息，获取 AgentCore CLI 在 Amazon Cognito 的帮助下为您的网关创建的访问令牌：
+  **令牌终端节点 **-在网关授权方配置**中的**发现 URL 中查找。如果您使用 API，则可以通过向网关发送[ListGateways](https://docs.amazonaws.cn/bedrock-agentcore-control/latest/APIReference/API_ListGateways.html)请求或请求来查找发现 URL。[ GetGateway ](https://docs.amazonaws.cn/bedrock-agentcore-control/latest/APIReference/API_GetGateway.html)
+  **客户端 ID ** — 在 Amazon Cognito 用户池中查找。如果您使用 API，则可以向与您的网关关联的用户池发送[ListUserPools](https://docs.amazonaws.cn/cognito-user-identity-pools/latest/APIReference/API_ListUserPools.html)[DescribeUserPool](https://docs.amazonaws.cn/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPool.html)请求或请求。
+  **客户端密钥 ** — 在 Amazon Cognito 用户池中查找应用程序客户端信息。如果您使用 API，则可以发送[DescribeUserPoolClient](https://docs.amazonaws.cn/cognito-user-identity-pools/latest/APIReference/API_DescribeUserPoolClient.html)请求，指定与您的网关关联的客户端 ID 和用户池 ID。

首先，使用以下方法之一收集这些值。选择以下方法之一：

**Example**  

1. 获取**代币终端节点**：

   1. 在 [ https://console.aws.amazon.com/bedrock-agentcore/home \# 处打开 AgentCore 控制台](https://console.amazonaws.cn/bedrock-agentcore/home#)。

   1. 从左侧导航窗格中选择**网关**。

   1. 在**网关**部分中，选择您的网关。

   1. 在 “**入站身份**” 部分中，记下以下值：
      +  **允许的客户端 **-可以访问网关的客户端 ID。
      +  **Discovery URL ** — 格式应为`https://cognito-idp.${Region}.amazonaws.com/${UserPoolId}/.well-known/openid-configuration`。存储以下值：
        +  `${UserPoolId}`— 从发现 URL 中提取。
        +  **令牌端点 **-选择发现 URL 链接，然后在`token_endpoint`字段中查找值。

1. 获取**客户端 ID ** 和**客户端密钥**：

   1. 在 [https://console.aws.amazon.com/cognito](https://console.amazonaws.cn/cognito) 打开 Amazon Cognito 控制台。

   1. 在左侧导航窗格中，选择**用户池**。

   1. 选择与您的网关关联的用户池 ID。

   1. 在左侧导航窗格中，选择**应用程序客户端**。

   1. 选择一个应用程序客户端，其**客户端 ID ** 与您的令牌终端节点允许的客户端相匹配。存储 ID 值。

   1. 在 “**客户端密钥” 下**，选择 “**显示客户端密钥” ** 并存储该值。

1. 在终端中运行该 AgentCore `get-gateway`命令并在`--gateway-identifier`参数中指定您的网关 ID，如以下示例所示：

   ```
   aws bedrock-agentcore-control get-gateway --gateway-identifier my-gateway-id
   ```

1. 在回复中，请注意`authorizerConfiguration`字段`discoveryUrl`中的内容：
   + 存储 URL `${UserPoolId}` 中的内容。格式应该是`https://cognito-idp.${Region}.amazonaws.com/${UserPoolId}/.well-known/openid-configuration`。
   + 存储`allowedClients`值。这些是可以访问令牌端点的客户端 ID。
   + 在浏览器`discoveryUrl`中导航到并存储该`token_endpoint`值。

1. 在终端中运行 Amazon Cognito `describe-user-pool-client` 命令，在`--user-pool-id`参数中指定用户池 ID，在`--client-id`字段中指定允许的客户端 ID，如以下示例所示：

   ```
   aws cognito-idp describe-user-pool-client --user-pool-id my-user-pool-id --client-id my-client-id
   ```

1. 存储该`ClientSecret`值。

1. 运行以下 Python 代码，将令牌端点、客户端 ID 和客户端密钥存储为变量：

   ```
   import requests
     import boto3
   
     # Initialize AWS clients
     agentcore_client = boto3.client("bedrock-agentcore-control")
     cognito_client = boto3.client("cognito-idp")
   
     # Replace with your actual gateway ID
     gateway_id = "my-gateway-id"
   
     # Get discovery URL and first allowed client
     auth_config = agentcore_client.get_gateway(gatewayIdentifier=gateway_id)["authorizerConfiguration"]["customJWTAuthorizer"]
     discovery_url, client_id = auth_config["discoveryUrl"], auth_config["allowedClients"][0]
   
     # Get token endpoint from discovery URL
     discovery_url_json = requests.get(discovery_url).json()
     token_endpoint, user_pool_id = discovery_url_json["token_endpoint"], discovery_url_json["issuer"].split("/")[-1]
   
     # Get client secret
     client_secret = cognito_client.describe_user_pool_client(
         UserPoolId=user_pool_id,
         ClientId=client_id
     )["UserPoolClient"]["ClientSecret"]
   ```

其次，使用您收集的值从令牌端点访问令牌。选择以下方法之一：

**Example**  

1. 在终端中运行以下命令，替换令牌端点、客户端 ID 和客户端密钥值。

   ```
   curl --http1.1 -X POST ${TokenEndpoint} \
       -H "Content-Type: application/x-www-form-urlencoded" \
       -d "grant_type=client_credentials&client_id=${ClientId}&client_secret=${ClientSecret}"
   ```

   令牌在响应`access_token`字段中，而该`token_type`字段应指定`Bearer`。

1. 运行以下 Python 代码以获取您的访问令牌。该代码假定您存储了上一步中的`token_endpoint``client_id`、和`client_secret`值：

   ```
   import requests
     import json
   
     def get_access_token(token_endpoint, client_id, client_secret):
         headers={
             "Content-Type": "application/x-www-form-urlencoded"
         }
   
         payload={
             "grant_type": "client_credentials",
             "client_id": client_id,
             "client_secret": client_secret
         }
   
         response = requests.post(token_endpoint, headers=headers, data=payload)
         return response.json()
   
     # Replace the argument values as necessary, if you didn't previously store them as these variables
     access_token_response = get_access_token(
         token_endpoint=token_endpoint,
         client_id=client_id,
         client_secret=client_secret
     )
   
     access_token = access_token_response["access_token"]
   ```