Abir Rahman
Abir Rahman

Reputation: 41

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 :

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.

Upvotes: 0

Views: 949

Answers (1)

jarmod
jarmod

Reputation: 78563

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);
}

Upvotes: 1

Related Questions