

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

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

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

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

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

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

**Example**  

1. 获取令**牌端点**：

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

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

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

   1. 在 “**入站身份**” 部分中，记下以下值：
      +  **允许的客户**端-可以访问网关的客户端 ID。
      +  **发现 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.aws.amazon.com/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. 从响应中，请注意`discoveryUrl`来自该`authorizerConfiguration`字段的内容：
   + 存储来`${UserPoolId}`自 URL 的。格式应为`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"]
   ```