在通过$.ajax()登录到一个网站后,我试图向该网站发送第二个$.ajax()请求-但当我检查使用FireBug发送的报头时,请求中没有会话cookie。
我做错了什么?
在通过$.ajax()登录到一个网站后,我试图向该网站发送第二个$.ajax()请求-但当我检查使用FireBug发送的报头时,请求中没有会话cookie。
我做错了什么?
当前回答
使用
xhrFields: { withCredentials:true }
作为我的jQuery ajax调用的一部分只是解决方案的一部分。我还需要有从我的资源的选项响应返回的头:
Access-Control-Allow-Origin : http://www.wombling.com
Access-Control-Allow-Credentials : true
重要的是,OPTIONS调用的响应头中只有一个允许的“origin”,而不是“*”。我通过从请求中读取源并将其填充回响应来实现这一点——可能绕过了限制的最初原因,但在我的用例中,安全性并不是最重要的。
我认为有必要明确地提到只有一个源的要求,因为W3C标准允许空格分隔列表,但Chrome不允许! http://www.w3.org/TR/cors/#access-control-allow-origin-response-header 注意“在实践中”的部分。
其他回答
There are already a lot of good responses to this question, but I thought it may be helpful to clarify the case where you would expect the session cookie to be sent because the cookie domain matches, but it is not getting sent because the AJAX request is being made to a different subdomain. In this case, I have a cookie that is assigned to the *.mydomain.com domain, and I am wanting it to be included in an AJAX request to different.mydomain.com". By default, the cookie does not get sent. You do not need to disable HTTPONLY on the session cookie to resolve this issue. You only need to do what wombling suggested (https://stackoverflow.com/a/23660618/545223) and do the following.
1)在ajax请求中添加以下内容。
xhrFields: { withCredentials:true }
2)在不同子域的资源的响应头中添加以下内容。
Access-Control-Allow-Origin : http://original.mydomain.com
Access-Control-Allow-Credentials : true
使用
xhrFields: { withCredentials:true }
作为我的jQuery ajax调用的一部分只是解决方案的一部分。我还需要有从我的资源的选项响应返回的头:
Access-Control-Allow-Origin : http://www.wombling.com
Access-Control-Allow-Credentials : true
重要的是,OPTIONS调用的响应头中只有一个允许的“origin”,而不是“*”。我通过从请求中读取源并将其填充回响应来实现这一点——可能绕过了限制的最初原因,但在我的用例中,安全性并不是最重要的。
我认为有必要明确地提到只有一个源的要求,因为W3C标准允许空格分隔列表,但Chrome不允许! http://www.w3.org/TR/cors/#access-control-allow-origin-response-header 注意“在实践中”的部分。
把这个放在你的init函数中:
$.ajaxSetup({
xhrFields: {
withCredentials: true
}
});
它会起作用的。
如果您正在localhost或localhost上的端口(如localhost:8080)上进行开发,除了上面回答中描述的步骤外,还需要确保您没有在Set-Cookie报头中传递域值。 您不能在set - cookie报头中将域设置为localhost -这是不正确的-只需省略域即可。
查看cookie在本地主机与显式域和为什么asp.net不会在本地主机创建cookie ?
我有同样的问题,做一些检查我的脚本只是没有得到sessionid cookie。
通过查看浏览器中的sessionid cookie值,我发现我的框架(Django)将sessionid cookie以HttpOnly作为默认值传递。这意味着脚本不能访问sessionid值,因此不能将它与请求一起传递。有点荒谬的是,HttpOnly将是默认值,而很多东西都使用Ajax,这将需要访问限制。
为了解决这个问题,我改变了一个设置(SESSION_COOKIE_HTTPONLY=False),但在其他情况下,它可能是cookie路径上的“HttpOnly”标志