从AJAX获取受SSO保护的XHR资源



基本上我有一个在线API(XHR(,由SSO(基于Vouch的OAuth 2.0(保护。通过GET请求访问API后,您会得到错误302,并将您重定向到登录,然后如果成功验证,则返回API并安全访问资源。

我需要通过AJAX访问XHR资源(XML(;https://www.someUrl.com"来源-见下面的例子:

$.ajax({
url: "https://api.someUrl.com/xmlapi",
dataType: 'xml',
type: 'GET',

success: function(xmlDoc){

},
error: function(xmlDoc) {
console.log('Error: ' + xmlDoc.responseText);
}
});

如果cookie已经存在,则不会显示错误,并且一切运行顺利。如果cookie不在那里,那么我会得到CORS交叉原点错误。

如果用户未被认证";https://api.someUrl.com/xmlapi"将正常返回302(临时重定向(。但在AJAX中,没有发生任何改变。

开发人员工具正在显示以下流行错误:

Access to XMLHttpRequest at 'https://api.someUrl.com/xmlapi' from origin 'https://www.someUrl.com' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested 
resource.

我试图在服务器端更新"Access Control Allow Origin",但它没有响应。这似乎是因为浏览器不接受ajax中的重定向,尽管浏览器公司担心CORS问题。

检查了网络下的开发工具,这就是我所拥有的:

常规

Request URL: https://api.someUrl.com/xmlapi
Referrer Policy: strict-origin-when-cross-origin

响应标头

content-length: 145
content-type: text/html
date: Mon, 10 May 2021 10:51:09 GMT
location: https://login.someUrl.com/login?
url=https://api.someUrl.com/apixml&vouch-failcount=&X- 
Vouch-Token=&error=
server: nginx/1.18.0

请求标头

:authority: api.someUrl.com
:method: GET
:path: /apixml
:scheme: https
accept: application/xml, text/xml, */*; q=0.01
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
origin: https://www.someUrl.com
referer: https://www.someUrl.com/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site

我的设置是这样的:

  • 从www.XXX访问子域api上的资源。XXX
  • api.XXX重拨到子域登录。XXX
  • 如果登录成功,请重定向回api。XXX

上面可以工作,但当我将它移植到ajax时就不行了。

目的是让www.XXX用户验证ajax代码是否需要访问以保护资源(如api(。XXX。

如有任何建议,不胜感激。

我遇到此问题的原因是302(重定向(响应中完全缺少"Access Control Allow Origin"标头"卷曲-vhttps://api.com.au"帮我快速看球头。有"location"标头,但没有"Access Control Allow Origin"。因此,浏览器立即给出CORS错误,并忽略重定向。解决方案是将"Access Control Allow Origin"添加到NGINX中的302响应标头中。

这是NGINX中帮助解决问题的配置。

location @error401 {
# I added 3 lines below to solve CORS issue for 302 re-direct.
add_header Access-Control-Allow-Origin "https://www.XXX.com.au" always;
add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
# redirect to Vouch Proxy for login
return 302 https://login.XXX.com.au/login?url=$scheme://$http_host$request_uri&vouch-failcount=$auth_resp_failcount&X-Vouch-Token=$auth_resp_jwt&error=$auth_resp_err;
# you usually *want* to redirect to Vouch running behind the same Nginx config proteced by https
# but to get started you can just forward the end user to the port that vouch is running on
} 

最新更新