我已经设置了一个身份池,使用Python和boto3我可以检索访问密钥、密钥和会话令牌,我认为这是为未经身份验证的用户准备的:
import boto3
boto3.setup_default_session(region_name='us-east-1')
identity = boto3.client('cognito-identity',
region_name='us-east-1')
response = identity.get_id(AccountId='12344566', IdentityPoolId='us-east-1:XXXXXX')
identity_id = response['IdentityId']
print ("Identity ID: %s"%identity_id)
response = identity.get_open_id_token(IdentityId=identity_id)
token = response['Token']
print ("nToken: %s"%(token))
resp = identity.get_credentials_for_identity(IdentityId=identity_id)
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']
print ("nSecret Key: %s"%(secretKey))
print ("nAccess Key %s"%(accessKey))
一旦我有了这些细节,我就试图调用API网关。我使用javascript来完成这项任务,因为我还没有找到一种简单的方法来在python中实现我想要的结果:
var apigClient = apigClientFactory.newClient({
accessKey: 'aaaaaaaa',
secretKey: 'kkkkkkkk',
sessionToken: 'ssssss',
region: 'us-east-1'
});
apigClient.helloworldGet({},'')
.then(function(result){
console.log("success!: " + result);
}).catch( function(result){
console.log("FAIL: " + result);
});
此操作失败,响应为:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403
.
OPTIONS请求成功后,我已经正确设置了CORS。如果我使用我的主访问密钥和秘密来验证脚本的工作。如果我关闭get/helloworld方法上的IAM凭据要求,javascript将成功运行。我为Cognito为身份池设置的auth和unauth角色都附加了一个策略,这个策略看起来像这样:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "dsfdsafasfdsfasdf",
"Effect": "Allow",
"Action": [
"execute-api:Invoke"
],
"Resource": [
"arn:aws:execute-api:us-east-1:123456787:dsfsdfsdfs/dev/GET/helloworld"
]
}
]
}
我已经尝试将其作为托管策略和内联策略进行附加。
我在这里错过了什么?这是否与尝试以未经身份验证的用户身份访问有关(即使分配给该类型用户的角色附加了允许其访问API的策略)?
请注意,这里没有涉及Lamda,只是一个简单的任务定义位于ECS Autoscale组中,API网关在调用helloworld方法时会调用该组。详细内容如下:https://aws.amazon.com/blogs/compute/using-amazon-api-gateway-with-microservices-deployed-on-amazon-ecs/
原来这就是我检索令牌的方式。我在用
sessionToken = identity.get_open_id_token(IdentityId=identity_id)
当我请求凭据时,我应该从响应中获得令牌:
resp = identity.get_credentials_for_identity(IdentityId=identity_id)
secretKey = resp['Credentials']['SecretKey']
accessKey = resp['Credentials']['AccessKeyId']
sessionToken = resp['Credentials']['SessionToken']