我试图通过JQuery / Ajax从另一台服务器调用Java / Spring Web服务
单击按钮会触发代码:
var request = $.ajax({
xhrFields: {
withCredentials: true
},
method: "GET",
url: "http://<ipOfWebService>/api/myEndPoint/4313991?country=UK",
dataType: "xml",
crossDomain: true,
username: "basicUsername",
password: "basicPassword",
})
我按照Tomcat docs配置了CORS过滤器,将domainOfAjaxCall指定为允许的来源:
<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>ipAddress1,http://dev.ajaxCaller.com</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,Authorization</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>
在成功调用Web服务之前,系统会提示我输入用户名/密码:
我见过的大多数帖子都建议更换用户名&amp;带有beforeSend的密码,例如
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa( "basicUsername:basicPassword"))
},
不幸的是,尽管配置了CORS过滤器,但这会导致错误:
Failed to load http://<ipOfWebService>/api/myEndPoint/4313991?country=UK: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<domainOfAjaxCall>' is therefore not allowed access. The response had HTTP status code 401.
我也试过切换beforeSend:
headers: {
"Authorization": "Basic " + btoa("basicUsername:basicPassword")
},
结果相同。
我哪里错了?
答案 0 :(得分:0)
使用CORS标头将OPTIONS方法添加到您的Web服务,并将“Access-Control-Allow-Headers”设置为“Authorization”。
这应该有效!
为什么?
在跨域请求中使用Auth标头时,将首先发送对OPTIONS方法的请求。如果OPTIONS有正确的标题,它将继续执行您的请求中的方法。