2

我正在尝试使用 google-App-script 访问 AWS 的图像识别服务,为此,我正在尝试为 API 调用生成 AWS 签名,但响应显示错误消息。

{"__type":"InvalidSignatureException","message":"The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details."}

当我使用授权(AWS签名)尝试使用邮递员时,它工作正常。

下面是我在其中调用主函数的谷歌应用程序脚本代码

function main(){
    var headers=AwsHeader_('ListCollections');

  var t=UrlFetchApp.fetch("https://rekognition.us-east-1.amazonaws.com", {
      method: "POST",
      muteHttpExceptions:true,
    headers:headers
    });

  Logger.log("======>>"+t);
}


function hexSignature(signature){
    var signatureStr = '';
  Logger.log(signature.length);

    for (i = 0; i < signature.length; i++) {
      var byte = signature[i];
      Logger.log("byte"+byte);
      if (byte < 0)
        byte += 256;
      var byteStr = byte.toString(16);
      // Ensure we have 2 chars in our byte, pad with 0
      if (byteStr.length == 1) byteStr = '0'+byteStr;
      signatureStr += byteStr;

      Logger.log("signatureStr"+signatureStr);
    }  
  return signatureStr;
}


function get_signature(datestamp){

  var secret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  var region="us-east-1";
  var service="rekognition";


  var kdate = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, datestamp, "AWS4"+secret);
  var kregion = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, region, kdate);
  var kservice = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, service, kregion);
  var ksigning = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, "aws4_request", kservice);

  var signature=hexSignature(ksigning);
  return signature;

}

function AwsHeader_(service){

  var header={};
  var date=new Date();

  var formattedDate = Utilities.formatDate(date, "GMT", "yyyyMMdd'T'HHmmss'Z'");
  var onlydate=Utilities.formatDate(date, "GMT", "yyyyMMdd")


  var sign=get_signature(onlydate);

  header['Authorization']="AWS4-HMAC-SHA256 Credential=XXXXXXXXXX/"+onlydate+"/us-east-1/rekognition/aws4_request, SignedHeaders=cache-control;content-length;content-type;host;postman-token;x-amz-date;x-amz-target, Signature="+sign;
  header['X-Amz-Date']=formattedDate;
  header['Content-Type']="application/x-amz-json-1.1";
  header['X-Amz-Target']="RekognitionService."+service;
    return header;
}



我无法弄清楚我在代码中做错了什么,或者是生成签名的错误方法,请帮忙。

4

0 回答 0