对于上下文,我试图跨站点调用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),没有请求发送,错误消息访问受限制的URI被拒绝
要使调用在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>
答案 0 :(得分:1)
我终于找到了2个问题。
客户端:我将选项替换为:
xhrActiveBuilds = {
url: "http://localhost:8080/api/v1/ressource",
dataType: 'json',
xhrFields: { withCredentials: true },
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic <encoded_credentials>")
}
}
请注意我删除了用户名和密码,因为jQuery实现(see)
导致请求在FF上失败