如果正文使用AWS Signer V4包含非英文字符,则HTTP请求签名错误

时间:2019-07-11 07:30:24

标签: node.js amazon-web-services aws-sdk aws-elasticsearch

我正在使用Signing HTTP Requests to Amazon Elasticsearch Service中描述的相同签名方法。签名对于具有英语字段但不支持其他语言的文档可以很好地工作。

我尝试在内容类型中添加UTF-8,但这没有帮助。

// If your credentials don't work, export them at the terminal using the following commands:
// export AWS_ACCESS_KEY_ID="your-access-key"
// export AWS_SECRET_ACCESS_KEY="your-secret-key"

var AWS = require('aws-sdk');

var region = ''; // e.g. us-west-1
var domain = ''; // e.g. search-domain.region.es.amazonaws.com
var index = 'node-test';
var type = '_doc';
var id = '1';
var json = {
  "title": "عربي",
  "director": "Bennett Miller",
  "year": "2011"
}

indexDocument(json);

function indexDocument(document) {
  var endpoint = new AWS.Endpoint(domain);
  var request = new AWS.HttpRequest(endpoint, region);

  request.method = 'PUT';
  request.path += index + '/' + type + '/' + id;
  request.body = JSON.stringify(document);
  request.headers['host'] = domain;
  request.headers['Content-Type'] = 'application/json';
  // charset doesn't work too
  // request.headers['Content-Type'] = 'application/json; charset=utf-8';

  // Content-Length is only needed for DELETE requests that include a request
  // body, but including it for all requests doesn't seem to hurt anything.
  request.headers["Content-Length"] = request.body.length;

  var credentials = new AWS.EnvironmentCredentials('AWS');
  var signer = new AWS.Signers.V4(request, 'es');
  signer.addAuthorization(credentials, new Date());

  var client = new AWS.HttpClient();
  client.handleRequest(request, null, function(response) {
    console.log(response.statusCode + ' ' + response.statusMessage);
    var responseBody = '';
    response.on('data', function (chunk) {
      responseBody += chunk;
    });
    response.on('end', function (chunk) {
      console.log('Response body: ' + responseBody);
    });
  }, function(error) {
    console.log('Error: ' + error);
  });
}

使用上面的代码,我得到:

403 Forbidden
Response body: {
  "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."
}

0 个答案:

没有答案