How do I SET a Cookie (header) with XMLHttpRequest

2019-01-07 08:58发布

I'm trying to set a Cookie in a XSS request using XMLHttpRequest.

I found the XMLHttpRequest Specification, and section 4.6.2-5 does seem to suggest that setting Cookie, Cookie2, and some other headers are not allowed, but I was hoping there was a work around.

My (jQuery) code is below, but the resulting query fails as the cookie is NOT set.

$.ajax( {
  type : "POST",
  url : URL,
  data: SOAP_INBOX_MAIL_QUERY,
  dataType : "xml",
  async: false,
  beforeSend : function(xhr) {  
    var cookie = credentials["COOKIE"];
    console.info( "adding cookie: "+ cookie );          
    xhr.setRequestHeader('Cookie', cookie);
  },
  success : function(data, textStatus, xmLHttpRequest){


  },
  error : function(xhr, ajaxOptions, thrownError) {
    credentials = null;
  }
});

5条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-07 09:11

If your request at the same domain as jquery code, you can use jquery cookies plugin

查看更多
等我变得足够好
3楼-- · 2019-01-07 09:14

For security reasons, you will be unable to modify the header during an XMLHTTPRequest.

查看更多
Rolldiameter
4楼-- · 2019-01-07 09:18

This can be done. You need the following in the $.ajax call:

xhrFields: {
    withCredentials: true
}

(See the jQuery docs), and you'll also need the site you're making the request to to support CORS (they will at least need to allow you origin and also to set the Access-Control-Allow-Credentials HTTP header to true).

There's no question it works. You can do it over HTTPS, with Basic Auth, etc. jQuery will send everything (the auth header, cookies) if you tell it to (xhrFields) and the site provides the right CORS headers. Don't give up!

查看更多
你好瞎i
5楼-- · 2019-01-07 09:26

https://developer.mozilla.org/En/Server-Side_Access_Control

allow you origin and also to set the Access-Control-Allow-Credentials HTTP header to true

查看更多
我想做一个坏孩纸
6楼-- · 2019-01-07 09:32

If you set the cookie using document.cookie then when you send the request the cookie header will include it.

查看更多
登录 后发表回答