我的任务是对 flex 搜索API进行POST API调用,

https://search-test-search-fqa4l6ubylznt7is4d5yxlmbxy.us-west-2.es.amazonaws.com/klove-ddb/recipe/_search

我以前没有对AWS服务进行api调用的经验。

所以,我尝试了-

axios.post('https://search-test-search-fqa4l6ubylznt7is4d5yxlmbxy.us-west-2.es.amazonaws.com/klove-ddb/recipe/_search')
            .then(res => res.data)
            .then(res => console.log(res));

但是我收到了{“Message”:“User:匿名用户无权执行:es:ESHttpPost”}

我还 checkout 了一些IAM角色,并将AWSESFullAccess策略添加到我的配置文件中。

我仍然无法解决任何问题。

请帮我。

最佳答案

您看到错误User: anonymous is not authorized to perform: es:ESHttpPost的原因是,您在发出请求数据时没有让ElasticSearch知道您是谁-这就是为什么它说“匿名”的原因。

身份验证有两种方法,最简单的方法是使用elasticsearch library。使用此库,您将为IAM角色/用户提供一组凭据(访问密钥, secret 密钥)。它将使用它来创建签名的请求。签名的请求将使AWS知道谁在实际发出请求,因此不会以匿名方式接收,而是您自己。

使它起作用的另一种方法是将访问策略调整为基于IP:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "*"
            },
            "Action": "es:*",
            "Condition": {
                "IpAddress": {
                    "aws:SourceIp": [
                        "AAA.BBB.CCC.DDD"
                    ]
                }
            },
            "Resource": "YOUR_ELASTICSEARCH_CLUSTER_ARN"
        }
    ]
}

对于您在此处提供的ip(范围)的任何人,此特定策略将是开放的。但是,这将使您免于必须签署请求的麻烦。

有助于通过AWS ES设置elasticsearch-js的库是this one

一个有效的示例如下:
const AWS = require('aws-sdk')
const elasticsearch = require('elasticsearch')
const awsHttpClient = require('http-aws-es')

let client = elasticsearch.Client({
    host: '<YOUR_ES_CLUSTER_ID>.<YOUR_ES_REGION>.es.amazonaws.com',
    connectionClass: awsHttpClient,
    amazonES: {
        region: '<YOUR_ES_REGION>',
        credentials: new AWS.Credentials('<YOUR_ACCESS_KEY>', '<YOUR_SECRET_KEY>')
    }
});

client.search({
    index: 'twitter',
    type: 'tweets',
    body: {
        query: {
            match: {
                body: 'elasticsearch'
            }
        }
    }
})
.then(res => console.log(res));

08-07 23:59
查看更多