天天看點

通過nginx代理無密碼通路開啟了x-pack驗證的elasticsearch

在有些工具中,并沒有提供elasticsearch的使用者名密碼接口,而如果elasticsearch開啟了x-pack驗證,使用者名密碼又是必須參數。如果去修改工具實作,代價又太大,是以我們可以選擇使用nginx反向代理,使用nginx為請求增加驗證,達到無密碼通路相容老工具的目的。

首先,elasticsearch中配置允許通過請求頭來驗證:

http.cors.allow-headers: Authorization
           

然後我們先使用curl 加上-u -v參數來通路elasticsearch,觀察請求體:

curl --user elastic:123456 -v "http://127.0.0.1:11111"

* About to connect() to 127.0.0.1 port 11111 (#0)
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 11111 (#0)
* Server auth using Basic with user 'elastic'
> GET / HTTP/1.1
> Authorization: Basic ZWxhc3RpYzoxMjM0NTY=
> User-Agent: curl/7.29.0
> Host: 127.0.0.1:11111
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: nginx/1.12.2
< Date: Tue, 30 Oct 2018 07:42:06 GMT
< Content-Type: application/json; charset=UTF-8
< Content-Length: 491
< Connection: keep-alive
< 
{
  "name" : "es-wk-node-1",
  "cluster_name" : "es-wk1",
  "cluster_uuid" : "Dc1CiavHRzSCtt4yzImVrA",
  "version" : {
    "number" : "6.4.2",
    "build_flavor" : "default",
    "build_type" : "tar",
    "build_hash" : "04711c2",
    "build_date" : "2018-09-26T13:34:09.098244Z",
    "build_snapshot" : false,
    "lucene_version" : "7.4.0",
    "minimum_wire_compatibility_version" : "5.6.0",
    "minimum_index_compatibility_version" : "5.0.0"
  },
  "tagline" : "You Know, for Search"
}

           

通過與不加-u(–user)參數的對比,可以發現差别就是請求頭多了一個Authorization參數,而其值是固定的,是以我們在nginx中配置為請求添加此請求頭即可。

server {
        listen       11111;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            # proxy_set_header user elastic:123456;
            proxy_set_header Authorization 'Basic ZWxhc3RpYzoxMjM0NTY=';
            proxy_pass http://127.0.0.1:19200;
        }
}
           

這時候去掉-u參數再使用curl通路elasticsearch發現就成功了。