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
专家
已审核 1 个月前
  • 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 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则