身份验证标头不发送 JQuery Ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18889983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:42:30  来源:igfitidea点击:

Authentication headers are not sending JQuery Ajax

ajaxweb-servicesjqueryauthentication

提问by N K

I have web server hosted in Apache Tomcat 7 with Basic authentication. I have Tomcat user 'tomcat' with role 'tomcat' and password 'tomcat'. Following are my web.xml file and script snippet in client side respectively.

我在带有基本身份验证的 Apache Tomcat 7 中托管了 Web 服务器。我有 Tomcat 用户“tomcat”,角色为“tomcat”,密码为“tomcat”。以下分别是我在客户端的 web.xml 文件和脚本片段。

Web.xml

网页.xml

<?xml version="1.0" encoding="ASCII"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name>testservice</display-name>
  <servlet>
    <description>JAX-RS Tools Generated - Do not modify</description>
    <servlet-name>testservice</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>testservice</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>testservice</web-resource-name>
            <url-pattern>/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
        </web-resource-collection>
        <auth-constraint>
            <role-name>tomcat</role-name>
        </auth-constraint>

        <user-data-constraint>
            <!-- transport-guarantee can be CONFIDENTIAL, INTEGRAL, or NONE -->
            <transport-guarantee>NONE</transport-guarantee>
        </user-data-constraint>
    </security-constraint>

    <login-config>
        <auth-method>BASIC</auth-method>
    </login-config>
</web-app>

Client script:

客户端脚本:

<script src="jquery-1.10.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
    $.ajax({
        type: "GET",
        beforeSend: function (request)
        {
            request.setRequestHeader("Authorization", "Basic  dG9tY2F0OnRvbWNhdA==");
        },
        url: "http://localhost:1222/testservice/rest/test/users",
        dataType:"jsonp",
        success: function(res) {
            alert(res); 
        },
        error: function(err) {
            alert(err);
        }
    });                    
</script>

I'm pretty sure about that there's no problem with Web Service and Basic authentication. But from client script, no authentication headers are sending. I tried header:("Authorization","Basic dG9tY2F0OnRvbWNhdA==")too. But request is sending without authentication headers. Any help will be appreciated.

我很确定 Web 服务和基本身份验证没有问题。但是从客户端脚本来看,没有发送任何身份验证标头。我也试过header:("Authorization","Basic dG9tY2F0OnRvbWNhdA==")了。但是请求是在没有身份验证标头的情况下发送的。任何帮助将不胜感激。

采纳答案by N K

Found that passing authentication via headers is not working with jQuery ajax with jsonp data type. So tried following and works fine.

发现通过标头传递身份验证不适用于 jsonp 数据类型的 jQuery ajax。所以尝试跟随并且工作正常。

$.ajax({
    type: "GET",
    url: "http://tomcat:tomcat@localhost:1222/testservice/rest/test/users",
    dataType:"jsonp",
    success: function(res) {
        alert(res); 
    },
    error: function(err) {
        alert(err);
    }
});  

function callbackMethod(data) {
    alert(data);
}

回答by mccannf

Two things to try:

尝试两件事:

1) Add the CORS Filter to your Tomcat configuration

1) 将 CORS 过滤器添加到您的 Tomcat 配置中

add the CORS Filterto your Tomcat configuration. Note Access-Control-Allow-Originshas been purposely left blank below, so no site has access via CORS. But the important parameter that is configured is Access-Control-Allow-Credentials.

CORS 过滤器添加到您的 Tomcat 配置中。注意Access-Control-Allow-Origins在下面故意留空,因此没有站点可以通过 CORS 访问。但配置的重要参数是Access-Control-Allow-Credentials.

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value></param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

2) Modify Your Ajax Call

2) 修改你的 Ajax 调用

Modify your beforeSendin your ajax call like so:

beforeSend像这样修改你的 ajax 调用:

$.ajax({
    type: "GET",
    beforeSend: function (request)
    {
        request.withCredentials = true;
        request.setRequestHeader("Authorization", "Basic  dG9tY2F0OnRvbWNhdA==");
    },
    url: "http://localhost:1222/testservice/rest/test/users",
    dataType:"jsonp",
    success: function(res) {
        alert(res); 
    },
    error: function(err) {
        alert(err);
    }
});           

Only other thing I noticed is that your web.xml might also need the following:

我注意到的另一件事是您的 web.xml 可能还需要以下内容:

<security-role>
  <role-name>tomcat</role-name>
</security-role>

Hope this helps.

希望这可以帮助。

回答by Ryan Anderson

mccannf got us 99% of the way there with a similar issue hover we switched up how we set the withCredentials property and this worked for us. notice we set the xhrFields property. This can been seen within the jQuery documentation for the ajax method here; http://api.jquery.com/jQuery.ajax/

mccannf 通过类似的悬停问题让我们完成了 99% 的工作,我们改变了设置 withCredentials 属性的方式,这对我们有用。注意我们设置了 xhrFields 属性。这可以在此处的 ajax 方法的 jQuery 文档中看到;http://api.jquery.com/jQuery.ajax/

$.ajax({
    type: "GET",
    xhrFields: { withCredentials: true }, 
    beforeSend: function (request)
    {
        request.setRequestHeader("Authorization", "Basic  dG9tY2F0OnRvbWNhdA==");
    },
    url: "http://localhost:1222/testservice/rest/test/users",
    dataType:"jsonp",
    succes: function(res) {
        alert(ers); 
    },
    error: function(err) {
        alert(err);
    }
});

However, we were not using jsonp, simple json.

但是,我们没有使用 jsonp,简单的 json。

回答by Héctor Espí Hernández

I haven't found a solution for this, only a workaround:

我还没有找到解决方案,只有一个解决方法:

Send the Authorization header using two headers, the standard one and a custom one for IE:

使用两个标头发送 Authorization 标头,一个是标准标头,另一个是用于 IE 的自定义标头:

beforeSend: function (jqXHR, settings) {
    if (self._hasAuthInfo()) {
        jqXHR.setRequestHeader("Authorization", self._makeAuthHeader());
        jqXHR.setRequestHeader("IEAuth", self._makeAuthHeader());
    }
}

The server side will check both (the second one only if IE and if the standard one is not present)

服务器端将检查两者(仅当 IE 和标准不存在时才检查第二个)