在 AWS API Gateway 中使用 Cognito Authorization 模拟,需要在 API Gateway 中配置相应的授权和集成。以下是使用 Python 和 AWS CLI 的示例代码来模拟授权。
创建一个 Cognito User Pool 并设置一个用户。
创建一个 API Gateway REST API 并在资源中添加一个 GET 方法。
创建 Cognito 授权作为 API Gateway 的授权提供程序。
aws apigateway create-authorizer \
--rest-api-id \
--name Authorizer \
--type COGNITO_USER_POOLS \
--provider-arns \
--identity-source 'method.request.header.Authorization'
aws apigateway put-method \
--rest-api-id \
--resource-id \
--http-method GET \
--authorization-type COGNITO_USER_POOLS \
--authorizer-id \
--request-parameters '{"method.request.header.Authorization":"true"}'
aws apigateway put-integration \
--rest-api-id \
--resource-id \
--http-method GET \
--type HTTP \
--integration-http-method POST \
--uri \
--passthrough-behavior WHEN_NO_MATCH \
--request-parameters '{"integration.request.header.Authorization":"method.request.header.Authorization"}'
aws apigateway create-deployment \
--rest-api-id \
--stage-name prod \
--description 'New deployment'
import requests
username = 'user_name'
password = 'password'
data = {
'grant_type': 'password',
'client_id': '',
'username': username,
'password': password,
}
# 获取访问令牌
response = requests.post('https://.auth..amazoncognito.com/oauth2/token', data=data)
access_token = response.json()['access_token']
# 访问 API
response2 = requests.get('https:///prod/', headers={'Authorization': f'Bearer {access_token}'})
print(response2.json())
以上是一个示例代码,它展示了如何使用 AWS CLI 和 Python 来创建一个在 API Gateway 中使用 Cognito Authorization 模拟的 API。