how to configure aws sdk client with cognito identity Pool , cognito user pool as a identity provider. i am trying to using dynamodb on react client

0
 const main = async (oN: string) => {
    

   const { accessToken, idToken } = (await fetchAuthSession()).tokens ?? {};

    const REGION = 'ap-south-1';

    let COGNITO_ID = `cognito-idp.${REGION}.amazonaws.com/ap-south-*****`;

    const loginData = `${COGNITO_ID}: ${authToken}`;
    const client = new DynamoDBClient({
      region: REGION,
      credentials: fromCognitoIdentityPool({
        clientConfig: { region: REGION }, 
        identityPoolId: 'identity pool id here',
        logins: {
          // Optional tokens, used for authenticated login.
          COGNITO_ID: authToken as unknown as string,

        },
      }),
    });
    console.log(client, 'client');

    const docClient = DynamoDBDocumentClient.from(client);
    console.log(docClient, 'docClient');

    const command = new PutCommand({
      TableName: 'the dynamodb table name',
      Item: {
        pk: 'LK',
        sk: 'test-sk',
        oN: oN,
      },
    });
    console.log(command, 'command');
    console.log(docClient, 'docClient');
    const response = await docClient.send(command);
    console.log(response);
    return response;
  };

it is returing this Error

TypeError tokenOrProvider is not a function Call Stack  undefined   vendor.js:16269:22  resolveLogins   vendor.js:16263:44  provider   vendor.js:16424:40  undefined   vendor.js:16439:18  coalesceProvider   vendor.js:70444:23  SignatureV4.credentialProvider   vendor.js:70466:30  SignatureV4.signRequest   vendor.js:71777:40  SignatureV4.sign   vendor.js:71732:25  undefined   vendor.js:2875:38

Debnath
asked 5 months ago407 views
2 Answers
0
Accepted Answer

It looks like there might be an issue with how you're providing the authentication token (authToken) to the fromCognitoIdentityPool function in the AWS SDK. The logins parameter expects an object where the key is the identity provider name, and the value is the authentication token. Here's a revised version of your code:

import { DynamoDBClient, PutCommand } from '@aws-sdk/client-dynamodb';
import { DynamoDBDocumentClient } from '@aws-sdk/lib-dynamodb';
import { fromCognitoIdentityPool } from '@aws-sdk/credential-provider-cognito-identity';

const main = async (oN: string) => {
    const { accessToken, idToken } = (await fetchAuthSession()).tokens ?? {};

    const REGION = 'ap-south-1';
    const COGNITO_IDENTITY_POOL_ID = 'your-identity-pool-id'; // Replace with your actual Identity Pool ID

    const logins = {
        [`cognito-idp.${REGION}.amazonaws.com/${COGNITO_IDENTITY_POOL_ID}`]: idToken,
    };

    const client = new DynamoDBClient({
        region: REGION,
        credentials: fromCognitoIdentityPool({
            clientConfig: { region: REGION }, 
            identityPoolId: COGNITO_IDENTITY_POOL_ID,
            logins,
        }),
    });

    const docClient = DynamoDBDocumentClient.from(client);

    const command = new PutCommand({
        TableName: 'your-dynamodb-table-name', // Replace with your actual table name
        Item: {
            pk: 'LK',
            sk: 'test-sk',
            oN: oN,
        },
    });

    try {
        const response = await docClient.send(command);
        console.log(response);
        return response;
    } catch (error) {
        console.error('Error executing DynamoDB PutCommand:', error);
        throw error;
    }
};

const fetchAuthSession = async () => {
    // Implement your logic to fetch authentication tokens (idToken, accessToken) here
    // This might involve using Amazon Cognito's authentication flow or any other authentication mechanism you're using.
};

main('example-data');

Ensure you replace placeholders like 'your-identity-pool-id' and 'your-dynamodb-table-name' with your actual Identity Pool ID and DynamoDB table name.

Additionally, make sure your fetchAuthSession function returns the correct authentication tokens. If you're using Cognito, it might involve calling CognitoUser.getSession() or a similar method.

If the issue persists, consider logging the actual values of idToken and authToken to the console to ensure they are being retrieved correctly before the DynamoDB operation.

profile pictureAWS
Renato
answered 5 months ago
profile picture
EXPERT
reviewed 25 days ago
  • const logins = { [cognito-idp.${REGION}.amazonaws.com/${COGNITO_IDENTITY_POOL_ID}]: ${idToken}, };

0

its solved after passing the idToken within backtick

  const logins = {
      [`cognito-idp.${REGION}.amazonaws.com/${COGNITO_IDENTITY_POOL_ID}`]: `${idToken}`,
    };

Debnath
answered 5 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions