Javascript 在 Chrome 或 Firefox 中,jquery $.ajax 调用导致 401 未经授权的响应,但在 IE 中有效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29782222/
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-23 03:58:26  来源:igfitidea点击:

jquery $.ajax call results in 401 unauthorized response when in Chrome or Firefox, but works in IE

javascriptjqueryajaxhttp-status-code-401

提问by AK3800

I have a script running on a web page that needs to use the JQuery $.ajax method (currently using jquery 1.7.2) to submit several GET requests to a service endpoint on a different domain. I have the ajax call working in IE (9, 10, 11), but it fails with a 401 Unauthorized response in Firefox and Chrome. Part of the additional error message in Chrome is "Full authentication is required to access this resource".

我在需要使用 JQuery $.ajax 方法(当前使用 jquery 1.7.2)向不同域上的服务端点提交多个 GET 请求的网页上运行一个脚本。我有 ajax 调用在 IE (9, 10, 11) 中工作,但它在 Firefox 和 Chrome 中失败并显示 401 Unauthorized 响应。Chrome 中附加错误消息的一部分是“访问此资源需要完全身份验证”。

My ajax call is setup like this (dataType is "json" for these requests that fail, and async is true):

我的 ajax 调用是这样设置的(对于这些失败的请求,dataType 是“json”,而 async 是 true):

    $.ajax({
      url: url,
      type: "GET",
      async: isAsync,
      dataType: dataType,
      username: user,
      password: pswd,
      success: function (response, status) {
         // success code here
      },
      failure: function (response, status) {
         // failure code here
      },
      complete: function (xhr, status) {
         // on complete code here
      }
   });

I am passing in the username and password required to access the service and this works in IE. I was understanding that the JQuery ajax function would handle the authentication correctly, so if a response comes back indicating that authorization is required, it would use the credentials that were provided to make that request correctly. Am I missing something here? Do I need to manually add the Authorization header for this to work?

我正在传递访问服务所需的用户名和密码,这在 IE 中有效。我了解到 JQuery ajax 函数将正确处理身份验证,因此如果返回指示需要授权的响应,它将使用提供的凭据正确发出该请求。我在这里错过了什么吗?我是否需要手动添加 Authorization 标头才能使其工作?

UPDATE: Here is the request, response, and cookie info reported by Chrome and IE via the F12 debugging tools (some info replaced with [...removed...])

更新:这是 Chrome 和 IE 通过 F12 调试工具报告的请求、响应和 cookie 信息(一些信息替换为 [...removed...])

Chrome (42.0.2311.90 m)

铬 (42.0.2311.90 m)

Response Headers

access-control-allow-credentials:true access-control-allow-origin:[...removed...] access-control-expose-headers: cache-control:private,max-age=0,must-revalidate connection:keep-alive content-encoding:gzip content-length:296 content-type:text/html;charset=ISO-8859-1 date:Tue, 21 Apr 2015 20:55:12 GMT expires:Tue, 21 Apr 2015 20:55:12 GMT p3p:CP="NON DSP COR CURa PSAa PSDa OUR NOR BUS PUR COM NAV STA" set-cookie:JSESSIONID=qd-app-1348vf1vrksvc76oshcwirvjp.qd-app-13;Path=/;Secure;HttpOnly set-cookie:NSC_vt1.sbmmzefw.dpn!-!IUUQT=ffffffff09091c3945525d5f4f58455e445a4a42378b;path=/;secure;httponly status:401 Unauthorized vary:Accept-Encoding version:HTTP/1.1 www-authenticate:Basic realm="Rally ALM"

Request Headers

:host:rally1.rallydev.com :method:GET :path:[...removed...] :scheme:https :version:HTTP/1.1 accept:application/json, text/javascript, /; q=0.01 accept-encoding:gzip, deflate, sdch accept-language:en-US,en;q=0.8 origin:[...removed...] referer:[...removed...] user-agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36

Response Cookies

JSESSIONID qd-app-1348vf1vrksvc76oshcwirvjp.qd-app-13 NSC_vt1.sbmmzefw.dpn!-!IUUQT ffffffff09091c3945525d5f4f58455e445a4a42378b

响应头

access-control-allow-credentials:true access-control-allow-origin:[...removed...] access-control-expose-headers: cache-control:private,max-age=0,must-revalidate connection :keep-alive content-encoding:gzip content-length:296 content-type:text/html;charset=ISO-8859-1 date:Tue, 21 Apr 2015 20:55:12 GMT expires:Tue, 21 Apr 2015 20 :55:12 GMT p3p:CP="NON DSP COR CURa PSAa PSDa OUR NOR BUS PUR COM NAV STA" set-cookie:JSESSIONID=qd-app-1348vf1vrksvc76oshcwirvjp.qd-app-13;Path=/;Secure;HttpOnly set -cookie:NSC_vt1.sbmmzefw.dpn!-!IUUQT=ffffffff09091c3945525d5f4f58455e445a4a42378b;path=/;secure;httponly status:401 未授权变化:Accept-Encoding version:HTTP/thenicR

请求头

:host:rally1.rallydev.com :method:GET :path:[...removed...] :scheme:https :version:HTTP/1.1 accept:application/json, text/javascript, /; q=0.01 accept-encoding:gzip, deflate, sdch accept-language:en-US,en;q=0.8 origin:[...removed...] referer:[...removed...] user-agent :Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36

响应 Cookie

JSESSIONID qd-app-1348vf1vrksvc76oshcwirvjp.qd-app-13 NSC_vt1.sbmmzefw.dpn!-!IUUQT ffffffff09091c3945525d5f4f58455e4437a4b4a4

IE 11

浏览器 11

Request Headers

Request GET [...removed...] Referer [...removed...] Accept
application/json, text/javascript, /; q=0.01 Accept-Language en-US Accept-Encoding gzip, deflate User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko Host [...removed...] Connection Keep-Alive Cache-Control no-cache Cookie
JSESSIONID=qd-app-08xmftgye78tde1b0wzcl2kit4m.qd-app-08; NSC_vt1.sbmmzefw.dpn!-!IUUQT=ffffffff09091c3145525d5f4f58455e445a4a42378b; RALLY-Detail-treeCollapsed=false; ZSESSIONID=RpKo5acfRqmjPhW0vIU1rgurWmDhlka0lrGCY9MIWhU; SUBBUCKETID=713

Response Headers

Response HTTP/1.1 200 OK RallyRequestID qd-app-08xmftgye78tde1b0wzcl2kit4m.qd-app-0810353108 Expires Thu, 01 Jan 1970 00:00:00 GMT Content-Type text/javascript; charset=utf-8 ETag "0101c2c8d3463ee3c1a4f950d4142b7d3" P3P CP="NON DSP COR CURa PSAa PSDa OUR NOR BUS PUR COM NAV STA" Cache-Control private,max-age=0,must-revalidate Date Tue, 21 Apr 2015 20:58:17 GMT Connection keep-alive Set-Cookie ZSESSIONID=RpKo5acfRqmjPhW0vIU1rgurWmDhlka0lrGCY9MIWhU;Path=/;Domain=[...removed...];Secure;HttpOnly Set-Cookie SUBBUCKETID=713;Path=/;Domain=[...removed...];Secure;HttpOnly Content-Length 319

Cookies

Sent JSESSIONID qd-app-08xmftgye78tde1b0wzcl2kit4m.qd-app-08
Sent NSC_vt1.sbmmzefw.dpn!-!IUUQT ffffffff09091c3145525d5f4f58455e445a4a42378b Sent RALLY-Detail-treeCollapsed false Sent ZSESSIONID RpKo5acfRqmjPhW0vIU1rgurWmDhlka0lrGCY9MIWhU Sent SUBBUCKETID 713 Received ZSESSIONID RpKo5acfRqmjPhW0vIU1rgurWmDhlka0lrGCY9MIWhU At end of session [...removed...] / Yes Yes Received SUBBUCKETID 713 At end of session [...removed...] / Yes Yes

请求头

请求 GET [...removed...] Referer [...removed...] 接受
application/json, text/javascript, /; q=0.01 Accept-Language en-US Accept-Encoding gzip, deflate User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko Host [...removed...] Connection Keep -Alive Cache-Control no-cache Cookie
JSESSIONID=qd-app-08xmftgye78tde1b0wzcl2kit4m.qd-app-08;NSC_vt1.sbmmzefw.dpn!-!IUUQT=ffffffff09091c3145525d5f4f58455e445a4a42378b; RALLY-Detail-treeCollapsed=false; ZSESSIONID=RpKo5acfRqmjPhW0vIU1rgurWmDhlka0lrGCY9MIWhU;子桶ID=713

响应头

响应 HTTP/1.1 200 OK RallyRequestID qd-app-08xmftgye78tde1b0wzcl2kit4m.qd-app-0810353108 到期 1970 年 1 月 1 日星期四 00:00:00 GMT Content-Type text/javascript; charset=utf-8 ETag "0101c2c8d3463ee3c1a4f950d4142b7d3" P3P CP="NON DSP COR CURa PSAa PSDa OUR NOR BUS PUR COM NAV STA" 缓存控制私有,max-age=0, Tumus-revalidate2051 日期2051 :17 GMT Connection keep-alive Set-Cookie ZSESSIONID=RpKo5acfRqmjPhW0vIU1rgurWmDhlka0lrGCY9MIWhU;Path=/;Domain=[...removed...];Secure;HttpOnly Set-Cookie SUBBUCKETID=713;Path=/;Domain=删除...];安全;HttpOnly 内容长度 319

饼干

发送JSESSIONID QD-APP-08xmftgye78tde1b0wzcl2kit4m.qd-APP-08
已发送NSC_vt1.sbmmzefw.dpn! -会话[...删除的IUUQT ffffffff09091c3145525d5f4f58455e445a4a42378b发送拉力赛详细信息,treeCollapsed假发送ZSESSIONID RpKo5acfRqmjPhW0vIU1rgurWmDhlka0lrGCY9MIWhU发送SUBBUCKETID 713收到ZSESSIONID RpKo5acfRqmjPhW0vIU1rgurWmDhlka0lrGCY9MIWhU在年底。 ..] / 是 是 已收到 SUBBUCKETID 713 在会话结束时 [...删除...] / 是 是

采纳答案by AK3800

I came across a jquery forum postthat had some additional information regarding this issue. Based on what I found there, I added this to the $.ajax call:

我遇到了一个jquery 论坛帖子,其中包含有关此问题的一些附加信息。根据我在那里找到的内容,我将其添加到 $.ajax 调用中:

  beforeSend: function (xhr) {
     xhr.setRequestHeader('Authorization', makeBaseAuth(user, pswd));
  }

where makeBaseAuth() uses the btoa() function like this:

其中 makeBaseAuth() 使用 btoa() 函数是这样的:

   makeBaseAuth: function(user, pswd){ 
      var token = user + ':' + pswd;
      var hash = "";
      if (btoa) {
         hash = btoa(token);
      }
      return "Basic " + hash;
   }

That appears to be working in Chrome now, I'm not getting a login prompt or a 401 response, the request is going through and I get the expected response. I also removed the option xhrFields: { withCredentials: true }as that didn't appear to be necessary. For some reason this isn't working in Firefox yet, and in the Firefox debugger I can't actually get at the javascript to do any decent debugging to see what the problem is, the way this script works is its loaded into a web page as an anonymous script and I don't have any control over that. I have a way to get at the script in IE and Chrome, but not Firefox for some reason. I'll consider this a win just getting it to work in Chrome, thanks to everyone for prodding me in the right direction!

这似乎现在在 Chrome 中工作,我没有收到登录提示或 401 响应,请求正在通过,我得到了预期的响应。我还删除了该选项,xhrFields: { withCredentials: true }因为这似乎没有必要。出于某种原因,这在 Firefox 中还不起作用,在 Firefox 调试器中,我实际上无法使用 javascript 进行任何体面的调试以查看问题所在,该脚本的工作方式是将其加载到网页中作为匿名脚本,我对此没有任何控制权。我有办法在 IE 和 Chrome 中获取脚本,但由于某种原因不能在 Firefox 中获取。我会认为这是一个胜利,只要让它在 Chrome 中工作,感谢大家推动我朝着正确的方向前进!