I've been trying to get Cognito to work for more than a day now.
Our scenario that I want to get to work is the "Authenticate with a Third Party and Access AWS Services with an Identity Pool" one on this page (https://docs.amazonaws.cn/en_us/cognito/latest/developerguide/cognito-scenarios.html)
Currently I generate credentials with AWS.EnvironmentCredentials
, create a new CognitoIdentity
and use that to call getOpenIdTokenForDeveloperIdentity
in our backend.
AWS.config.credentials = new AWS.EnvironmentCredentials(...);
AWS.config.update({region: 'cn-north-1'});
const cognitoidentity = new AWS.CognitoIdentity({apiVersion: '2014-06-30'});
const params = {
IdentityPoolId: 'cn-north-1:XXXXXX',
Logins: {
'<DeveloperProviderName>': identifierStr,
},
};
This works fine an I can receive the neccecary token
and identityId
that I return to my front end. There I exchange the token
and identityId
for credentials.
AWS.config.region = 'cn-north-1';
const cognitoidentity = new AWS.CognitoIdentity({apiVersion: '2014-06-30'});
const params = {
IdentityId: identityId,
Logins: {
'cognito-identity.cn-north-1.amazonaws.com.cn': token, //using the key for cn-north-1
}
};
cognitoidentity.getCredentialsForIdentity(params, (err, data) => {
if (err){
//handle error
} else {
//get credentials
//using AccessKeyId and SecretKey and SessionToken to use AWS services
}
});
Here I'll get the error InvalidAccessKeyId: The AWS Access Key Id you provided does not exist in our records.
Why do I get this error? And how do I resolve it?
I was thinking that I might need to change the credentials configuration for the backend, as the sample code in the identity pool suggests, but this gives the error Missing credentials in config
on the server.
// Initialize the Amazon Cognito credentials provider
AWS.config.region = 'cn-north-1'; // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'cn-north-1:XXXXXXX',
});
edit: After some research I added SessionToken
to the configurations (additional to AccessKey and SecretKey), but get a new error AccessDenied
now. I checked in my role configurations and I have assigned the correct rights to my authenticated role, though.
I found the answer to my second error as well.
I was missing a correct bucket policy (since I am trying to access S3). The bucket policy needs to be updated with
{
"Version": "2012-10-17",
"Id": "Policy01",
"Statement": [
{
"Sid": "Statement01",
"Effect": "Allow",
"Principal": {
"AWS": <IdentityPoolAuthenticatedRole>
},
"Action": [
"s3:DeleteObject",
"s3:PutObject",
"s3:PutObjectAcl"
],
"Resource": "arn:aws-cn:s3:::<bucketName>/*" // <* or specified keyName>
},
...
// more statements
]
}
so the bucket knows requests from are okay, as far as I understand.
This blog post helped me to get on the right track, but it assumes you're setting up for unauthorized users and not using Identity Pools.