最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

我在 aws

网站源码admin29浏览0评论

我在 aws

我在 aws

我正在使用 aws-sdk v3 创建 dynamoDB 操作。 测试时,我收到错误“UnrecognizedClientException:请求中包含的安全令牌无效。”

  Unit test for DynamoDb ' verifies successful response

    UnrecognizedClientException: The security token included in the request is invalid.

      25 | const command = new GetItemCommand(params);
      26 | console.log(command)
    > 27 | const result = await this.client.send(command);
         | ^ ^
      28 | return { body: JSON.stringify(unmarshall(result.Item || {})) }; }
      29 | } catch (err: unknown) {
      30 | throw err;

这是代码。

import { BatchGetItemCommand, BatchWriteItemCommand, BatchWriteItemCommandOutput, DynamoDBClient, GetItemCommand, PutItemCommand, UpdateItemCommand } from '@aws-sdk/client-dynamodb';
import { marshall, unmarshall } from '@aws-sdk/util-dynamodb';

export class DynamoDb {
    private readonly tableName: string;
    private readonly client: DynamoDBClient;

    constructor(tableName = '') {
        this.client = new DynamoDBClient({
            region: 'ap-northeast-1',
            credentials: {
                accessKeyId: 'xxxx',
                secretAccessKey: 'xxxxx',
            },
        });
        this.tableName = tableName ? tableName : '';
    }

    public async get(keyName: string, key: string | number) {
        try {
            const params = {
                TableName: this.tableName,
                Key: marshall({ [keyName]: key }),
            };
            const command = new GetItemCommand(params);
            console.log(command)
            const result = await this.client.send(command);
            return { body: JSON.stringify(unmarshall(result.Item || {})) };
        } catch (err: unknown) {
            throw err;
        }
    }

    public async put(item: object) {
        try {
            const params = {
                TableName: this.tableName,
                Item: marshall(item),
            };
            const command = new PutItemCommand(params);
            return await this.client.send(command);
        } catch (err: unknown) {
            throw err;
        }
    }

    public async update(keyName: string, key: string | number, updateExpression: string, expressionAttributeValues: { [key: string]: any }) {
        try {
            const params = {
                TableName: this.tableName,
                Key: marshall({ [keyName]: key }),
                UpdateExpression: updateExpression,
                ExpressionAttributeValues: marshall(expressionAttributeValues),
                ReturnValues: 'ALL_NEW', // Return the updated attributes of the item
            };
            const command = new UpdateItemCommand(params);
            const result = await this.client.send(command);
            return { body: JSON.stringify(unmarshall(result.Attributes || {})) };
        } catch (err: unknown) {
            throw err;
        }
    }

    public async batchGet(keys: { [keyName: string]: string | number }[]) {
        try {
            const params = {
                RequestItems: {
                    [this.tableName]: {
                        Keys: keys.map((key) => marshall(key)),
                    },
                },
            };
            const command = new BatchGetItemCommand(params);
            const result = await this.client.send(command);
            const responses = result.Responses?.[this.tableName] || [];
            const items = responses.map((response) => unmarshall(response) as object);
            return { body: JSON.stringify(items) };
        } catch (err: unknown) {
            throw err;
        }
    }

    public async batchPut(items: object[]) {
        try {
            const putRequests = items.map((item) => ({
                PutRequest: {
                    Item: marshall(item),
                },
            }));

            const params = {
                RequestItems: {
                    [this.tableName]: putRequests,
                },
            };
            const command = new BatchWriteItemCommand(params);
            const result: BatchWriteItemCommandOutput = await this.client.send(command);
            return { body: JSON.stringify(result) };
        } catch (err: unknown) {
            throw err;
        }
    }
}

我已经明确写了访问密钥和秘密密钥,我做错了什么? 该密钥在另一个代码中使用,我可以毫无问题地连接到 DynamoDB。

回答如下:

您的凭据密钥一定有问题,请确保它们正确且仍然有效。

还要确保该角色不强制执行 MFA,如果强制执行,您将必须包含

AWS_SESSION_TOKEN
作为您的凭据的一部分。

我还建议您永远不要对凭据进行硬编码!甚至不用于测试。如果您在 AWS 中的测试使用 IAM 角色。如果您在本地进行测试,请使用

aws configure
在本地配置凭据。

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论