Search code examples
javascriptamazon-web-servicesamazon-cognitoaws-sdkamazon-transcribe

How to get the credentials using only Cognito Identity pool?


I'm looking to get temporary AWS credentials through the Cognito Identity pool. And then that credentials should access the AWS Transcribe service.

I've created an Identity pool and checked the option of unauthenticated user, so that I don't have to provide a token when I'm calling CognitoIdentityCredentials.

Then I attached the permission for transcribe service in the unauthenticated role(Cognito_TestIdentityPoolUnauth_Role-New).

But when I'm calling the CognitoIdentityCredentials, I'm not getting the credentials.

This is my code:-

    const AWS = require('aws-sdk');
    AWS.config.region = 'us-east-1';

    // Configure the credentials provider to use your identity pool
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
        identityPoolId: 'your_pool_id',
    });

    let accessKeyId, secretAccessKey, sessionToken;
    // Make the call to obtain credentials
    AWS.config.credentials.get(function(){
      // Credentials will be available when this function is called.
      accessKeyId = AWS.config.credentials.accessKeyId;
      secretAccessKey = AWS.config.credentials.secretAccessKey;
      sessionToken = AWS.config.credentials.sessionToken;
      console.log('data', accessKeyId, secretAccessKey, sessionToken);
    });
    

The acessKeyId, secretAccessKey and sessionToken is undefined. What am I missing here?


Solution

  • So to answer my own question. The latest credentials were somehow not being updated in the SDK. I'm also using the S3 service in the same function and the creds for that service are different. Here's the updated code which worked for me. And here's the thread that helped me.

        const creds = new AWS.CognitoIdentityCredentials({
          IdentityPoolId: 'identity_pool_id',
        })
    
        AWS.config.update({
          region: 'us-east-1',
          credentials: creds,
        });
    
        AWS.config.credentials.get(function () {
          // Credentials will be available when this function is called.
          const accessKeyId = AWS.config.credentials.accessKeyId;
          const secretAccessKey = AWS.config.credentials.secretAccessKey;
          const sessionToken = AWS.config.credentials.sessionToken;
          console.log(accessKeyId, secretAccessKey, sessionToken);
        });
    

    PS:- Using node v14.