Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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....

like image 467
ABCD Avatar asked Oct 26 '25 09:10

ABCD


1 Answers

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

like image 191
Private Avatar answered Oct 28 '25 22:10

Private



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!