6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsでAWS ElasticSearchへのHTTP リクエストの署名

Last updated at Posted at 2020-01-25

はじめに

情報保護を難しくなっている現代社会では、セキュリティ対応はますます重要になってきています。
Cloud技術の進化によって、セキュリティ対応しやすくなる部分もあります。

AWSのElasticeSearchサービスへのHTTP リクエストの署名方法を簡単にまとめてみます。

1. AWS SDKのライブラリを使う

AWSのドキュメントにある通り、署名したリクエストを送信できますが、検索のクエリなどはちょっと手間ですね。

参考URL: https://docs.aws.amazon.com/ja_jp/elasticsearch-service/latest/developerguide/es-request-signing.html

node.js
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) {
    // ....
  }

2. aws-elasticsearch-connectorモジュールを使う

Node.jsからElasticSearchへアクセスするには、ElasticSearchクライアントを使うと検索などに便利です。
aws-elasticsearch-connectorを利用して署名も簡単にできます。

2.1 aws-elasticsearch-connectorインストール

npm install --save aws-elasticsearch-connector @elastic/elasticsearch aws-sdk

2.2 profile利用例

node.js
const AWS = require('aws-sdk');
const { Client } = require('@elastic/elasticsearch');
const { AmazonConnection } = require('aws-elasticsearch-connector');
 
// Load AWS profile credentials
AWS.config.update({
  profile: 'my-profile'
});

 
const client = new Client({
  node: 'my-elasticsearch-cluster.us-east-1.es.amazonaws.com',
  Connection: AmazonConnection
});

2.3 .envにアクセスキー、シークレットキー利用例

AWS_ACCESS_KEY_ID=foo      # alias: AWS_ACCESS_KEY
AWS_SECRET_ACCESS_KEY=bar  # alias: AWS_SECRET_KEY
AWS_SESSION_TOKEN=xxx  //optional
node.js
const { Client } = require('@elastic/elasticsearch');
const { AmazonConnection } = require('aws-elasticsearch-connector');
 
const client = new Client({
  node: 'my-elasticsearch-cluster.us-east-1.es.amazonaws.com',
  Connection: AmazonConnection,
});

参考URL:https://github.com/compwright/aws-elasticsearch-connector#readme

2.4 検索結果

node.js
let searchResult = await client.search({
    index: 'xxx_index',
    body: {
      //...
    });

// ヒットしたデータ
let hits = searchResult.body.hits.hits;
// ヒットしたデータ数
let hitsCount = searchResult.body.hits.total;

ElasticSearchのクライアントAPI:
https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/client-usage.html

以上

6
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?