示例: AgentCore CLI 创建的默认网关和目标的授权
如果您使用 AgentCore CLI 创建网关和 Lambda 目标,则 CLI 会自动为您配置 JWT-based 入站授权和 IAM-based 出站授权。
如果您使用调用网关agentcore invoke,CLI 会自动处理身份验证。只有当您想以编程方式调用网关(例如,使用 AWS SDK 或curl)时,才需要执行以下步骤。
要进行编程访问,您需要通过以下方式进行授权:
您可以通过收集以下信息,获取 AgentCore CLI 在 Amazon Cognito 的帮助下为您的网关创建的访问令牌:
首先,使用以下方法之一收集这些值。选择以下方法之一:
例
- Console
-
- AWS CLI
-
-
在终端中运行 AgentCore get-gateway命令并在--gateway-identifier参数中指定您的网关 ID,如以下示例所示:
aws bedrock-agentcore-control get-gateway --gateway-identifier my-gateway-id
-
从响应中,请注意discoveryUrl来自该authorizerConfiguration字段的内容:
-
存储来${UserPoolId}自 URL 的。格式应为https://cognito-idp.${Region}.amazonaws.com/${UserPoolId}/.well-known/openid-configuration。
-
存储allowedClients值。这些是可以访问令牌端点的客户端 ID。
-
在浏览器discoveryUrl中导航到并存储该token_endpoint值。
-
在终端中运行 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
-
存储该ClientSecret值。
- AWS Python SDK (Boto3)
-
-
运行以下 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"]
其次,使用您收集的值从令牌端点访问令牌。选择以下方法之一:
例
- curl
-
-
在终端中运行以下命令,替换令牌端点、客户端 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。
- Python requests package
-
-
运行以下 Python 代码以获取您的访问令牌。该代码假设您存储了上一步中的token_endpointclient_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"]