为什么 Chrome 和 Firefox 在使用基本身份验证调用 CORS ajax 时行为不同?

Why Chrome and Firefox have not the same behaviour with CORS ajax call with basic auth?

对于上下文,我正在尝试跨站点调用 API 需要用户使用基本身份验证进行身份验证。 服务于 API 的 Tomcat (7.0.43) 设置为允许跨源调用并进行身份验证。

我正在使用 jquery.ajax,传递以下选项:

xhrOtpions = {
        url: "http://localhost:8080/api/v1/ressource",
        dataType: 'json',
        username: "user",
        password: "pass",
        xhrFields: {
          withCredentials: true
        }
      }

使用Chrome (45),请求成功,使用Firefox (41),没有发送请求,错误信息是Access to restricted URI denied

为了在 Firefox 上进行调用,我更改了选项以应用我从相关 jquery 问题 on github 中读到的内容:

xhrActiveBuilds = {
        url: "http://localhost:8080/api/v1/ressource",
        dataType: 'json',
        username: "user",
        password: "pass",
        xhrFields: {
          withCredentials: true
        },            
        beforeSend: function (xhr) {
          xhr.setRequestHeader ("Authorization",  "Basic <encoded_credentials>")
        }
      }

这对FF没有任何改变,仍然是同样的错误。 在 Chrome,现在发送了预检 OPTIONS 请求,该请求因 403 禁止响应代码而失败。

Tomcat 服务器的 CORS 过滤器配置下方:

 <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>http://localhost:1081</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,Access-Control-Allow-Authorization</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个问题

  • 服务器端:我在cors.allowed.headers
  • 中添加了授权
  • 客户端:我将选项替换为:

    xhrActiveBuilds = {
      url: "http://localhost:8080/api/v1/ressource",
      dataType: 'json',
      xhrFields: { withCredentials: true },
      beforeSend: function (xhr) {
        xhr.setRequestHeader ("Authorization",  "Basic <encoded_credentials>")
      }
    }
    

请注意,我已经删除了用户名和密码,因为它们导致请求在 FF 上失败,因为 jQuery 实施 (see)