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
질문됨 5달 전472회 조회
2개 답변
0
수락된 답변

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
답변함 5달 전
profile picture
전문가
검토됨 한 달 전
  • 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
답변함 5달 전

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인