Get response header jquery ajax post Set-Cookie

noshitsherlock picture noshitsherlock · Oct 9, 2012 · Viewed 18.8k times · Source

I am using YouTrack for our tracking system. Youtrack comes with a rest webservice that you can call to get information from the system. I am having problem getting authorized and is getting forbidden all the time.

I do my post to their login, and I get the "login ok" respone, and if I check in firebug I can see that the headers are set correctly, but the cookie does not get created. For that I need to get the value from the response header, Set-Cookie.

The post looks like this.

      $.post(youTrackLoginUrl, { login: "restUser", password: "qwerty" }, function(data, text, xhr) {

      // do something 

      });

And the response and request looks like this.

Response headers:

HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: YTJSESSIONID=91541168A3E0FF9BBB02A8D427D70127; Path=/ jetbrains.charisma.main.security.PRINCIPAL=NjVlODRiZTMzNTMyZmI3ODRjNDgxMjk2NzVmOWVmZjNhNjgyYjI3MTY4YzBlYTc0NGIyY2Y1OGVlMDIzMzdjNTpyZXN0VXNlcg; Expires=Wed, 09-Oct-2013 09:47:48 GMT; Path=/ Cache-Control: no-cache, no-store, no-transform, must-revalidate Access-Control-Allow-Origin: a.domain.com Access-Control-Allow-Credentials: true Content-Type: application/xml;charset=UTF-8 Transfer-Encoding: chunked Date: Tue, 09 Oct 2012 09:47:48 GMT

Request:

POST /rest/user/login HTTP/1.1 Host: b.eelab.se User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1 Accept: / Accept-Language: sv-se,sv;q=0.8,en-us;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Connection: keep-alive Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Referer: http://intra.eelab.se/kontakt/it-vad-jobbar-vi-pa-nu/ Content-Length: 30 Origin: http://a.domain.com Pragma: no-cache Cache-Control: no-cache

I need the Set-Cookie value to create the cookie on the site. What can I do to achive this?

/Cheers.

Answer

Cooper Maruyama picture Cooper Maruyama · Feb 28, 2014

Try this:

function createCookie(name,value,days) {
  if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

$.post(youTrackLoginUrl, { login: "restUser", password: "qwerty" }, function(data, text, xhr) {

  data_set_cookie = data.match(/Set-Cookie:\s([^;]+);/)[1];
  createCookie(data_set_cookie.split("=")[0],data_set_cookie.split("=")[1],365); //sets cookie for 1 year

});