I have a web application built with AWS Amplify and Cognito used for authentication/authorization. Cognito User Pools is the identity provider.
Users are grouped into Cognito User Pools groups based on what permissions they should have.
I want some users to be part of multiple groups (e.g. Admin users) which should have the sum of these group's permissions. But since the user can only assume one role I need to be able to switch roles in the app.
I tried accomplishing this by using the getCredentialsForIdentity:
const cognito_identity = new AWS.CognitoIdentity({ apiVersion: '2014-06-30', region: 'eu-central-1' });
var params = {
IdentityId: 'some_identity',
CustomRoleArn: 'arn:aws:iam::<account_id>:role/editors',
};
cognito_identity.getCredentialsForIdentity(params, function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
When invoking the above code it fails with NotAuthorizedException: Access to Identity '`some_identity' is forbidden.
What do I need to do to make it work?
After including the Logins property in the parameters to getCredentialsForIdentity it worked:
async function switchRoles(region, identityId, roleArn, cognitoArn) {
const user = await Auth.currentUserPoolUser();
const cognitoidentity = new AWS.CognitoIdentity({ apiVersion: '2014-06-30', region });
const params = {
IdentityId: identityId,
CustomRoleArn: roleArn,
Logins: {
[cognitoArn]: user
.getSignInUserSession()
.getIdToken()
.getJwtToken(),
},
};
return cognitoidentity
.getCredentialsForIdentity(params)
.promise()
.then(data => {
return {
accessKeyId: data.Credentials.AccessKeyId,
sessionToken: data.Credentials.SessionToken,
secretAccessKey: data.Credentials.SecretKey,
expireTime: data.Credentials.Expiration,
expired: false,
};
})
.catch(err => {
console.log(err, err.stack);
return null;
});
}