Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I SET a Cookie (header) with XMLHttpRequest in JavaScript?

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;   } }); 
like image 920
barryred Avatar asked Feb 23 '10 17:02

barryred


People also ask

How do I set cookies in XMLHttpRequest?

var xhr = new XMLHttpRequest(); xhr. open("GET", url, false); xhr. withCredentials = true; xhr. setRequestHeader('Cookie', 'mycookie=cookie'); xhr.

How do you set a cookie header?

The Set-Cookie HTTP response header is used to send a cookie from the server to the user agent, so that the user agent can send it back to the server later. To send multiple cookies, multiple Set-Cookie headers should be sent in the same response.

Can you set a cookie in JavaScript?

Create a Cookie with JavaScriptJavaScript can create, read, and delete cookies with the document. cookie property. With JavaScript, a cookie can be created like this: document.

How do I get the response header cookie?

Just set the Set-Cookie header in the response from the server side code. The browser should save it automatically. As a developer, you may be able to inspect the value of the cookies using "Developer Tools". And the same cookie will be sent in subsequent requests to the same domain, until the cookie expires.


2 Answers

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!

like image 190
terrycojones Avatar answered Sep 22 '22 12:09

terrycojones


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

like image 32
Gabriel McAdams Avatar answered Sep 21 '22 12:09

Gabriel McAdams