Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.8k views
in Technique[技术] by (71.8m points)

amazon web services - aws signatureThe request signature we calculated does not match the signature you provided

I am trying to invoke API gateway using AWS signature in nodejs. but I am getting "The request signature we calculated does not match the signature you provided" error, couldn't figure out where is the issue.

const AWS = require('aws-sdk')
    var axios = require('axios');
var aws4 = require('aws4');
var crypto = require('crypto-js');

const REGION = process.env.REGION || 'eu-west-1';
const ASSUME_ROLE_ARN = process.env.ASSUME_ROLE_ARN || '';
const API_ID_PARAMETER = process.env._API_ID_PARAMETER ;

exports.handler = async(event) => {

    var mappedbody = event.body;
    console.log('mappedbody : ' + mappedbody);
    var sts = new AWS.STS({
            region: REGION
        });
    console.log('sts success')

    const getCrossAccountCredentials = async() => {
        return new Promise((resolve, reject) => {
            const timestamp = (new Date()).getTime();
            const params = {
                RoleArn: ASSUME_ROLE_ARN,
                RoleSessionName: `tewt-${timestamp}`,
                DurationSeconds: 3600
            };
            console.log('RoleSessionName : ' + params.RoleSessionName)
            sts.assumeRole(params, (err, data) => {
                if (err)
                    reject(err);
                else {
                    resolve({
                        accessKeyId: data.Credentials.AccessKeyId,
                        secretAccessKey: data.Credentials.SecretAccessKey,
                        sessionToken: data.Credentials.SessionToken,
                    });
                }
            });
        });
    }
    try {

        const tempdata = await getCrossAccountCredentials();
        var data = JSON.parse(JSON.stringify(tempdata));
        console.log(data);
        console.log(data.accessKeyId);
        console.log(data.secretAccessKey);

        const creds = {
            accessKeyId: data.accessKeyId,
            secretAccessKey: data.secretAccessKey,
            sessionToken: data.sessionToken
        };
        console.log('AWS.SSM start')

        var ssm = new AWS.SSM({
                apiVersion: '2014-11-06',
                region: REGION,
                credentials: creds
            });

        console.log('AWS.SSM end')
        const {
            Parameter
        } = await ssm
            .getParameter({
                Name: API_ID_PARAMETER
            })
            .promise();
        console.log(Parameter.Value)

     
        var hashedPayload = crypto.SHA256(mappedbody).toString();
      
        let request = {
            service: 'execute-api',
            host: `${Parameter.Value}.execute-api.${REGION}.amazonaws.com`,
            method: 'POST',
            url: `https://${Parameter.Value}.execute-api.${REGION}.amazonaws.com/dev/insert`,
            path: '/dev/insert',
            data: mappedbody, // object describing the mappedbody
            body: JSON.stringify(mappedbody),
            headers: {
                'Content-Type': 'application/json',
                'X-Amz-Content-Sha256': hashedPayload,

            }
        };
        console.log('request: ' + request);
        let signedRequest = aws4.sign(request, creds);
        console.log('signedReguest : ' + JSON.stringify(signedRequest));
        delete signedRequest.headers['Host'];
        delete signedRequest.headers['Content-Length'];
        delete signedRequest.headers['Content-Type'];
        const res = await axios(signedRequest);
        console.log('Data:', res.data);
        console.log('StatusCode:', res.statusCode);

        var responseBody = '';
        var response = '';
        if (res.statusCode === '200') {

            responseBody = {
                Code: 202,
                Description: "The request was successfully accepted"
            };
            response = {
                "statusCode": 202,
                "body": JSON.stringify(responseBody),
                "isBase64Encoded": false
            };
        }
        
        return response
    } catch (err) {
        console.log('Error:', err);
        var responseBody = '';
        var response = '';
        responseBody = {
            Code: 500,
            Description: "Service unavailable"
        };
        response = {
            "statusCode": 500,
            "body": JSON.stringify(responseBody),
            "isBase64Encoded": false
        };
        return response

    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...