Jsessionid cookie in javascript

Why is jQuery’s .ajax() method not sending my session cookie?

After logging in via $.ajax() to a site, I am trying to send a second $.ajax() request to that site — but when I check the headers sent using FireBug, there is no session cookie being included in the request. What am I doing wrong?

I did not get what u mean but I can say if I paste the request url in browser address bar and check Firebug again, I can see the cookie in headres sent to the server. Any solutions?

the browser will still create cookies set by the server during a ajax request, jquery or otherwise. Did you check the response to the ajax request and ensure cookies came back from the server to be set? There could be a problem with the server code such that it is not even setting the cookie, etc.

12 Answers 12

I am operating in cross-domain scenario. During login remote server is returning Set-Cookie header along with Access-Control-Allow-Credentials set to true.

The next ajax call to remote server should use this cookie.

CORS’s Access-Control-Allow-Credentials is there to allow cross-domain logging. Check https://developer.mozilla.org/En/HTTP_access_control for examples.

For me it seems like a bug in JQuery (or at least feature-to-be in next version).

  1. Cookies are not set automatically from AJAX response (citation: http://aleembawany.com/2006/11/14/anatomy-of-a-well-designed-ajax-login-experience/) Why?
  2. You cannot get value of the cookie from response to set it manually (http://www.w3.org/TR/XMLHttpRequest/#dom-xmlhttprequest-getresponseheader) I’m confused.. There should exist a way to ask jquery.ajax() to set XMLHttpRequest.withCredentials = «true» parameter.
Читайте также:  Пользовательский интерфейс java swing

ANSWER: You should use xhrFields param of http://api.jquery.com/jQuery.ajax/

The example in the documentation is:

It’s important as well that server answers correctly to this request. Copying here great comments from @Frédéric and @Pebbl:

Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding. The above example would fail if the header was wildcarded as: Access-Control-Allow-Origin: *

Origin: http://foo.example Cookie: pageAccess=2 

Server should respond with:

Access-Control-Allow-Origin: http://foo.example Access-Control-Allow-Credentials: true [payload] 

Thanks for the answer 🙂 just a quick addition, it might be worth mentioning Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding. The above example would fail if the header was wildcarded as: Access-Control-Allow-Origin: * developer.mozilla.org/en-US/docs/Web/HTTP/…

None of this worked for me unfortunately. If I run the same request from AngularJS it works, but from jQuery, even with these suggestions the session Cookie is not passed. (jQuery v2.1.1)

(O.O) You saved me from various painful hours. What a perfect answer! Thanks! I needed to add these in public root .htaccess of my website: Header set Access-Control-Allow-Origin «localhost» Header set Access-Control-Allow-Credentials «true»

AJAX calls only send Cookies if the url you’re calling is on the same domain as your calling script.

This may be a Cross Domain Problem.

Maybe you tried to call a url from www.domain-a.com while your calling script was on www.domain-b.com (In other words: You made a Cross Domain Call in which case the browser won’t sent any cookies to protect your privacy).

In this case your options are:

  • Write a small proxy which resides on domain-b and forwards your requests to domain-a. Your browser will allow you to call the proxy because it’s on the same server as the calling script.
    This proxy then can be configured by you to accept a cookie name and value parameter which it can send to domain-a. But for this to work you need to know the cookie’s name and value your server on domain-a wants for authentication.
  • If you’re fetching JSON objects try to use a JSONP request instead. jQuery supports these. But you need to alter your service on domain-a so that it returns valid JSONP responds.

Glad if that helped even a little bit.

It’s also worth noting that cookies can be set to a specific path so if you cookie was set with path=/something and you are requesting the page /another then the cookie will not be sent. When you request the page /something the cookie will be sent as expected. So check the code that sets the cookie as well.

@albanx Yes, if the requirements I mentioned are set. It’s just a normal request like any other and as such sends cookies.

«The cookie/session info was NOT sent» making my login code stop working. I get stuck for hours without knowing that I’m browsing my web at 0.0.0.0:5000 and making AJAX request to localhost:5000 and thinking they are the same. In fact they are NOT the same! Thank you for saving my coding-life

as part of my jQuery ajax call was only part of the solution. I also needed to have the headers returned in the OPTIONS response from my resource:

Access-Control-Allow-Origin : http://www.wombling.com Access-Control-Allow-Credentials : true 

It was important that only one allowed «origin» was in the response header of the OPTIONS call and not «*». I achieved this by reading the origin from the request and populating it back into the response — probably circumventing the original reason for the restriction, but in my use case the security is not paramount.

I thought it worth explicitly mentioning the requirement for only one origin, as the W3C standard does allow for a space separated list -but Chrome doesn’t! http://www.w3.org/TR/cors/#access-control-allow-origin-response-header NB the «in practice» bit.

Put this in your init function:

You saved my day! On the method level withCredentials didn’t work for me. But globaly like this it finally works! Thanks.

be careful with it, because it will send cookies to all requests, ether for other domains(which is not expect this and fail request by require Access-Control-Allow-Credentials)

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) Add the following to your ajax request.

2) Add the following to your response headers for resources in the different subdomain.

Access-Control-Allow-Origin : http://original.mydomain.com Access-Control-Allow-Credentials : true 

Источник

newspaint

So you make a HTTP request using the http library and you want the cookies returned by the remote webserver (maybe for a later request, a session cookie for example)?

The approach I ended up taking in Node.JS was to inspect the response.headers[“set-cookie”] field which is set to an array of cookies if they have been given in the server response.

var http = require( "http" ); var url = require( "url" ); var urlstring = "http://www.voa.com/"; var parsedurl = url.parse( urlstring ); var options = < hostname: parsedurl.hostname, port: ( parsedurl.port || 80 ), // 80 by default method: 'GET', path: parsedurl.path, headers: < >, >; var request = http.request( options, function ( response ) < // display returned cookies in header var setcookie = response.headers["set-cookie"]; if ( setcookie ) < setcookie.forEach( function ( cookiestr ) < console.log( "COOKIE:" + cookiestr ); >); > var data = ""; response.on( "data", function ( chunk ) < data += chunk; >); response.on( "end", function () < console.log( "STATUS:" + response.statusCode ); console.log( " DATA:" + data ); >); > ); request.on( "error", function( err ) < console.error( "ERROR:" + err ); >); request.end(); // let request know it is finished sending

This will output cookie information like:

COOKIE:JSESSIONID=7bcc3a128; Path=/

If you want to send cookies with your request add a header to the options you pass the request, e.g.:

var cookies = [ "JSESSIONID=c2aa6fa21", "site_ip=10.18.32.12", ]; options.headers["Cookie"] = cookies.join( "; " );

Источник

Русские Блоги

Прошло много времени с тех пор, как я написал блог, и писать не о чем. Недавно я столкнулся с проблемой JSESSIONID. Онлайн-заявление немного расплывчато, особенно когда возникнет проблема с перезаписью URL. Некоторые говорят, что файлы cookie отключены на на стороне клиента, а некоторые говорят, что первое посещение. Вот резюме

Что такое JSESSIONID

Если честно, мне сначала было немного стыдно это увидеть, я так давно не читал эту вещь, когда пишу Java.

Прежде всего, JSESSIONID — это файл cookie, а контейнер сервлета (tomcat, jetty) используется для записи сеанса пользователя.

Когда сажать JSESSIONID

Когда сеанс создается, то есть когда вызывается request.getSession (), мы не будем говорить о getSession. Следует добавить, что при доступе к html сеанс не создается. Страница JSP создает сеанс по умолчанию. Вы можете отключить автоматическое создание сеанса на странице JSP.

Перезапись URL

Когда сервер создает сеанс в памяти, требуется файл cookie.В дополнение к настройке Set-Cookie в заголовке запроса контейнеры, такие как tomcat, имеют механизм перезаписи URL. Этот механизм является восходящей стратегией, когда cookie на стороне клиента недоступен. Идентификатор сеанса передается путем добавления; jsessionid = xxx после URL-адреса, так что даже если Cookie недоступен, доступность сеанса может быть гарантировано, но сеанс отображается в самом URL. Это небезопасно, поэтому основные онлайн-утверждения согласованы.

Но наиболее важный вопрос — как Tomcat узнает, что клиентский cookie недоступен. Я импортировал отладку и отслеживание исходного кода Tomcat по идее, есть некоторые расхождения между разными версиями, и он должен быть примерно таким же

Tomcat имеет org.apache.catalina.connector.Response, который является целевым классом Response. Существует два метода перезаписи URL, а именно encodeRedirectURL с участием encodeURL , encodeRedirectURL Вызывается при перенаправлении, encodeURL Вроде бы вызывается вручную, поэтому по умолчаниюПерезапись URL происходит только при перенаправлении. Код этих двух методов похож, далее основное внимание уделяется encodeRedirectURL

/** * Encode the session identifier associated with this response * into the specified redirect URL, if necessary. * * @param url URL to be encoded * @return true if the URL was encoded */ @Override public String encodeRedirectURL(String url) < if (isEncodeable(toAbsolute(url))) < return (toEncoded(url, request.getSessionInternal().getIdInternal())); >else < return (url); >> 

Комментарий к методу очень четкий, при необходимости вставьте идентификатор сеанса в перенаправленный URL. Посмотри снова isEncodeable Метод, я добавил китайские аннотации для ключевых мест

    *
  • The request we are responding to asked for a valid session *
  • The requested session ID was not received via a cookie *
  • The specified URL points back to somewhere within the web * application that is responding to this request *

Какие звонки Request Объект isRequestedSessionIdFromCookie Чтобы определить, доступен ли cookie на стороне клиента, внутренняя логика также очень проста, то есть прочитайте, передан ли в запросе cookie JSESSIONID. Некоторые люди в Интернете сказали, что первое посещение,Фактически, пока клиент не передает JSESSIONID, Tomcat предполагает, что Cookie недоступен.

Источник

Оцените статью