Elasticsearch:Shield身份验证在AJAX调用中不起作用

Abt*_*Pst 5 ajax jquery elasticsearch

我正在尝试使用屏蔽身份验证向elasticsearch发送ajax调用

$.ajax({
        url: 'http://localhost/test2/test/_search',
        type: 'POST',
        //contentType: 'application/json; charset=UTF-8',
        crossDomain: true,
        dataType: 'json',
        username: "admin", 
        password: "admin123",
        data: JSON.stringify(queryBody),
        success: function(response) {
                alert(response)
                var data = response.hits.hits;
                var titleArray = [];
                //alert(data.length);
                if (data.length > 0) {
                /*
                   if (data.length > 5)
                       data.length=5;
                */
                   for (var i = 0; i < data.length; i++) {              
                        if(data[i].fields.Title[0].indexOf(settings.fieldValue) > -1)
                                        {
                                            titleArray.push(data[i].fields.DocumentID[0]+":"+data[i].fields.Title[0]);
                                        }
                                    }
                responseS(titleArray);
                titleArray=[];
                } else {    }  
        },
        error: function(jqXHR, textStatus, errorThrown) {
                       var jso = jQuery.parseJSON(jqXHR.responseText);
                       alert('section', 'error', '(' + jqXHR.status + ') ' + errorThrown + ' --<br />' + jso.error);
               }
});
Run Code Online (Sandbox Code Playgroud)

但我得到:

POST http:// localhost:9200/test2/test/_search 401(未经授权)

我也尝试过:

$.ajax({
                            url: 'http://admin:admin123@localhost/test2/test/_search',
                            type: 'POST',
                            //contentType: 'application/json; charset=UTF-8',
                            crossDomain: true,
                            dataType: 'json',
                            data: JSON.stringify(queryBody),
                            success: function(response) {
                                alert(response)
                                var data = response.hits.hits;

                                var titleArray = [];

                                //alert(data.length);
                                if (data.length > 0) {
                                    /*
                                    if (data.length > 5)
                                        data.length=5;
                                    */
                                    for (var i = 0; i < data.length; i++) {

                                        if(data[i].fields.Title[0].indexOf(settings.fieldValue) > -1)
                                        {

                                            titleArray.push(data[i].fields.DocumentID[0]+":"+data[i].fields.Title[0]);
                                        }
                                    }

                                    responseS(titleArray);
                                    titleArray=[];

                                } else {

                                }


                            },

                            error: function(jqXHR, textStatus, errorThrown) {
                                var jso = jQuery.parseJSON(jqXHR.responseText);
                                alert('section', 'error', '(' + jqXHR.status + ') ' + errorThrown + ' --<br />' + jso.error);
                            }
                        });
Run Code Online (Sandbox Code Playgroud)

但我得到了同样的401错误.

接下来我试过了:

    $.ajax({
                                    url: 'http://localhost/test2/test/_search',
                                    type: 'POST',
                                    //contentType: 'application/json; charset=UTF-8',
                                    crossDomain: true,
                                    dataType: 'json',
                                    data: JSON.stringify(queryBody),
                                    beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa("admin:admin123"));
},                                   success: function(response) {
                                        alert(response)
                                        var data = response.hits.hits;

                                        var titleArray = [];

                                        //alert(data.length);
                                        if (data.length > 0) {
                                            /*
                                            if (data.length > 5)
                                                data.length=5;
                                            */
                                            for (var i = 0; i < data.length; i++) {

                                                if(data[i].fields.Title[0].indexOf(settings.fieldValue) > -1)
                                                {

                                                    titleArray.push(data[i].fields.DocumentID[0]+":"+data[i].fields.Title[0]);
                                                }
                                            }

                                            responseS(titleArray);
                                            titleArray=[];

                                        } else {

                                        }


                                    },

                                    error: function(jqXHR, textStatus, errorThrown) {
                                        var jso = jQuery.parseJSON(jqXHR.responseText);
                                        alert('section', 'error', '(' + jqXHR.status + ') ' + errorThrown + ' --<br />' + jso.error);
                                    }
                                });
Run Code Online (Sandbox Code Playgroud)

但现在我明白了

XMLHttpRequest无法加载http:// localhost:9200/test2/test/_search.请求标头字段预检响应中的Access-Control-Allow-Headers不允许授权.localhost /:1 Uncaught SyntaxError:意外的令牌u

通过ajax调用将弹性用户名和密码发送到弹性的正确方法是什么?

这是我的elasticsearch.yml

action.disable_delete_all_indices: true

http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-headers: "Authorization, X-Requested-With, Content-Type, Content-Length"
http.cors.allow-credentials: true

bootstrap.mlockall: true

# For reference: https://www.elastic.co/guide/en/elasticsearch/guide/current/_limiting_memory_usage.html

# controls how much heap space is allocated to fielddata. When you run a query that requires access to new field values,
# it will load the values into memory and then try to add them to fielddata. If the resulting fielddata size would
# exceed the specified size, other values would be evicted in order to make space.
indices.fielddata.cache.size:  40%

# The fielddata circuit breaker limits the size of fielddata to 60% of the heap, by default.
indices.breaker.fielddata.limit: 60%

# The request circuit breaker estimates the size of structures required to complete other parts of a request,
# such as creating aggregation buckets, and limits them to 40% of the heap, by default.
indices.breaker.request.limit: 40%

# The total circuit breaker wraps the request and fielddata circuit breakers to ensure that the combination
# of the two doesn’t use more than 70% of the heap by default.
indices.breaker.total.limit: 70%
#shield.enabled: false
shield:
  authc:
    realms:
      native1:
        type: native
        order: 0
    realms:
      esusers:
        type: esusers
        order: 1
        files:
          users: ElasticSearch\elasticsearch-2.3.1\elasticsearch-2.3.1\config\shield\users
          users_roles: ElasticSearch\elasticsearch-2.3.1\elasticsearch-2.3.1\config\shield\users_role
Run Code Online (Sandbox Code Playgroud)

Val*_*Val 2

解决此问题的方法是配置 CORS 以接受文件Authorization中的标头elasticsearch.yml

http.cors.allow-headers: "Authorization, X-Requested-With, Content-Type, Content-Length"
Run Code Online (Sandbox Code Playgroud)

另请确保您的elasticsearch.yml文件中有以下三个设置:

http.cors.enabled: true
http.cors.allow-origin: /https?:\/\/localhost(:[0-9]+)?/
http.cors.allow-credentials: true
Run Code Online (Sandbox Code Playgroud)