ABCD
ABCD

Reputation: 820

How could I generate temporary credentials using Cognito Identity pool for accessing aws services?

I have a cognito user pool and identity pool. I have created an user in user pool. I got the tokens i.e. access, refresh, id tokens using lambda for that user. Now I want to generate the temporary credentials i.e. access key and secrete access key for that user to access the aws services. How could I do this? This is piece of code i used to generate tokens.

var authenticationDetails = new cognito.AuthenticationDetails(authenticationData);

    var userData = {
        Username : '*****',
        Pool : userPool
    };

var cognitoUser = new cognito.CognitoUser(userData);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function (result) {
console.log(result);

what changes should i do in this to get credentials? Thank you....

Upvotes: 4

Views: 5193

Answers (1)

Private
Private

Reputation: 1771

IN the below code i am retrieving tokens along with temporary cred's based on federated identities.

var data = {
  UserPoolId: YOURUSER_POOL_ID,
  ClientId: YOURAPP_CLIENT_ID,
};
var userPool = new cognito.CognitoUserPool(data);
var cognitoUser = userPool.getCurrentUser();
if (cognitoUser != null) {
  cognitoUser.getSession(function(err, session) {
    if (err) {
      console.log(err);
      return;
    }

    console.log('session validity: ' + session.isValid());
    console.log('session Identity token: ' + session.getIdToken().getJwtToken());

    AWS.config.region = YOURREGION;
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId : YOURIDENTITY_POOL_ID, 
      Logins : {
        // Change the key below according to the specific region your user pool is in.
        'cognito-idp.YOURREGIONNAME.amazonaws.com/YOURUSERPOOLID': session.getIdToken().getJwtToken()
      }
    });

    AWS.config.credentials.get(function(err,data) {
      if (!err) {
        var id = AWS.config.credentials.identityId;
        var key = AWS.config.credentials.accessKeyId;
        var secretkey = AWS.config.credentials.secretAccessKey;
        var sessionToken = AWS.config.credentials.sessionToken;
        console.log('Cognito Identity ID '+ id);
        console.log('Cognito Key '+ key);
        console.log('Cognito Secret Key '+ secretkey);
        console.log('Cognito SessionToken '+ sessionToken);
      }
    });
  });
} 

Change the necessary parameters according to yours.

Hope it might help you

Upvotes: 2

Related Questions