简体   繁体   中英

Getting 'The security token included in the request is invalid.' when trying to get a pre signed url for s3

Basically I'm trying to get a pre-signed URL for the putObject method in S3. I send this link back to my frontend, which then uses it to upload the file directly from the client.

Here's my code :

const AWS = require("aws-sdk");

const s3 = new AWS.S3({
    accessKeyId: process.env.AWS_IAM_ACCESS,
    secretAccessKey: process.env.AWS_IAM_SECRET,
    region: 'ap-southeast-1',
});

const getPreSignedUrlS3 = async (data) => {

    try {

       //DO SOMETHING HERE TO GENERATE KEY

        const options = {
            Bucket: process.env.AWS_USER_CDN,
            ContentType: data.type,
            Key: key,
            Expires: 5 * 60
        };

        return new Promise((resolve, reject) => {
            s3.getSignedUrl(
                "putObject", options,
                (err, url) => {
                    if (err) {
                        reject(err);
                    }
                    else resolve({ url, key });
                }
            );
        });

    } catch (err) {
        console.log(err)
        return {
            status: 500,
            msg: 'Failed to sync with CDN, Please try again later!',
        }
    }
}

I'm getting the following error from the aws sdk : The security token included in the request is invalid.

Things I have tried :

  • Double check the permissions from my IAM user. Even made bucket access public for testing. My IAM user is given full s3 access policy.
  • Tried using my root user security key and access details. Still got the same error.
  • Regenerated new security credentials for my IAM user. I don't have any MFA turned on.

I'm following this documentation.

SDK Version : 2.756.0

I've been stuck on this for a while now. Any help is appreciated. Thank you.

Pre-signed URLs are created locally in the SDK so there's no need to use the asynchronous calls.

Instead, use a synchronous call to simplify your code, something like this:

const getPreSignedUrlS3 = (Bucket, Key, ContentType, Expires = 5 * 60) => {
    const params = {
        Bucket,
        ContentType,
        Key,
        Expires
    };
    return s3.getSignedUrl("putObject", params);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM