Remove cookies from jquery ajax calls - session

I would do jquery ajax calls discarding every cookie, so I can have a new session for every call.
Is there a way to do this?
Thanks

AJAX request is exactly an HTTP request (XMLHTTPRequest). Cookies get sent back and forth in the AJAX request-response headers in order to maintain the state of user session across multiple HTTP requests.
HTTP is an inherently stateless protocol and hence cookies are used to maintain the state of user's session across multiple HTTP requests.
Instead of removing cookies host all your static components(like images) in a Cookie-free Domain. The following url might might give you some info in this,
http://www.ravelrumba.com/blog/static-cookieless-domain/

As Harun pointed out, maybe you should consider a wider solution than deleting a session cookie that will alter the whole user session and not only your AJAX call.
To litteraly answer your question, you could delete the cookie you've set (provided you've set by yourself and not by another framework):
$.cookie("session", null);
$.ajax( url, [settings] )
But, that's probably not the good solution because you will delete the whole user session at each ajax call. You should tell us more about what you are doing so that we could help you.

Related

Send ajax requests without cookies in the same domain?

I see that google or twitter autosuggest's sends ajax requests which are very lightweight since they don't send any cookies with the request. I was wondering how do they do it?
I googled about ways but i found ways like sending via CORS but they are sending the request to the same domain.
Any idea or ways on how to do that.
I am using chrome.
Thanks in advance
These are the two options I can think of to answer your question:
Option 1: Set withCredentials: false when using XMLHttpRequest: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials
Option 2: Delete cookies before sending the request and (in the case of wanted re-use restore them afterwards from temp variable) like so:
Get cookies and store them somewhere (f.i. in global var)
Delete cookies from domain
Send AJAX request
Restore cookies from variable

stop sending google analytics cookie with ajax calls

I am using Google Analytics on an ajax heavy website. I have a timer on the website, making an XMLHttpRequest every few seconds. With every request, browser sends the Google Analytics cookies to my server. Since my server don't use these cookies, I want to somehow prevent the browser to include these cookies in every request.
including _gaq.push(['_setDomainName', 'none']); did not help!
any ideas ?
Google Analytics cookies are first party cookies.
They will be sent as every other first party cookie for each request to the same domain (and subdomains)
You need to use a different domain for your Ajax calls (but I guess it would bring some other troubles, but solutions exist : Cross Domain request )
Using a path like www.domain.com/ajax/ under which all ajax calls would happen, and create empty __utma, __utmb, __utmc and __utmz cookies with a cookie path of /ajax/ would fail.
The empy cookies will not supersede the domain cookie for these requests , but will be added first in the request order
I ended up limiting analytic cookies to my domain, then created a sub-domain for the feed ajax call running on a timer, then used jsonp for cross site compatibility. Hope this helps someone else out there.

How can AJAX validate user?

When user is on the page you can use session or cookies to check who is he.
But when AJAX is used, for example, for sending an answer, sending page have no contact with user. How can it check is it real registered user, or just spambot sending this by headers?
What is the common practice for AJAX user validation?
AJAX requests contain the same cookies like regular requests. Besides that you can send any arguments like session IDs with the AJAX request.
Actually, for the server it makes absolutely no difference if a request is made through an XmlHttpRequest object or not. Most frameworks add an X-Requested-With: XMLHttpRequest header though but that's completely optional.
So.. whatever means you use to pass your session data, simply ensure it's also available to the script called with your AJAX request:
If you have a session id passed via GET/POST, include it in your request's arguments.
If cookies are needed, ensure they are send to the file. If it's in the same folder like the current file or a descendant of it you are usually safe. If it's on another (sub-)domain you might get problems - not only with cookies but alsowith cross-domain AJAX which usually isn't allowed due to the same-origin policy browsers have.

Can an AJAX response set a cookie?

Can an AJAX response set a cookie? If not, what is my alternative solution? Should I set it with Javascript or something similar?
According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.
Quotation:
If the user agent supports HTTP State Management it should persist,
discard and send cookies (as received in the Set-Cookie response
header, and sent in the Cookie header) as applicable.
Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.
AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.
For the record, be advised that all of the above is (still) true only if the AJAX call is made on the same domain. If you're looking into setting cookies on another domain using AJAX, you're opening a totally different can of worms. Reading cross-domain cookies does work, however (or at least the server serves them; whether your client's UA allows your code to access them is, again, a different topic; as of 2014 they do).
Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.

How do HttpOnly cookies work with AJAX requests?

JavaScript needs access to cookies if AJAX is used on a site with access restrictions based on cookies. Will HttpOnly cookies work on an AJAX site?
Edit: Microsoft created a way to prevent XSS attacks by disallowing JavaScript access to cookies if HttpOnly is specified. FireFox later adopted this. So my question is: If you are using AJAX on a site, like StackOverflow, are Http-Only cookies an option?
Edit 2: Question 2. If the purpose of HttpOnly is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of HttpOnly?
Edit 3: Here is a quote from Wikipedia:
When the browser receives such a cookie, it is supposed to use it as usual in the following HTTP exchanges, but not to make it visible to client-side scripts.[32] The HttpOnly flag is not part of any standard, and is not implemented in all browsers. Note that there is currently no prevention of reading or writing the session cookie via a XMLHTTPRequest. [33].
I understand that document.cookie is blocked when you use HttpOnly. But it seems that you can still read cookie values in the XMLHttpRequest object, allowing for XSS. How does HttpOnly make you any safer than? By making cookies essentially read only?
In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.
<script type="text/javascript">
var req = null;
try { req = new XMLHttpRequest(); } catch(e) {}
if (!req) try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
if (!req) try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
req.open('GET', 'http://stackoverflow.com/', false);
req.send(null);
alert(req.getAllResponseHeaders());
</script>
Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...
Final Edit: Ahh, apparently both sites are wrong, this is actually a bug in FireFox. IE6 & 7 are actually the only browsers that currently fully support HttpOnly.
To reiterate everything I've learned:
HttpOnly restricts all access to document.cookie in IE7 & and FireFox (not sure about other browsers)
HttpOnly removes cookie information from the response headers in XMLHttpObject.getAllResponseHeaders() in IE7.
XMLHttpObjects may only be submitted to the domain they originated from, so there is no cross-domain posting of the cookies.
edit: This information is likely no longer up to date.
Yes, HTTP-Only cookies would be fine for this functionality. They will still be provided with the XmlHttpRequest's request to the server.
In the case of Stack Overflow, the cookies are automatically provided as part of the XmlHttpRequest request. I don't know the implementation details of the Stack Overflow authentication provider, but that cookie data is probably automatically used to verify your identity at a lower level than the "vote" controller method.
More generally, cookies are not required for AJAX. XmlHttpRequest support (or even iframe remoting, on older browsers) is all that is technically required.
However, if you want to provide security for AJAX enabled functionality, then the same rules apply as with traditional sites. You need some method for identifying the user behind each request, and cookies are almost always the means to that end.
In your example, I cannot write to your document.cookie, but I can still steal your cookie and post it to my domain using the XMLHttpRequest object.
XmlHttpRequest won't make cross-domain requests (for exactly the sorts of reasons you're touching on).
You could normally inject script to send the cookie to your domain using iframe remoting or JSONP, but then HTTP-Only protects the cookie again since it's inaccessible.
Unless you had compromised StackOverflow.com on the server side, you wouldn't be able to steal my cookie.
Edit 2: Question 2. If the purpose of Http-Only is to prevent JavaScript access to cookies, and you can still retrieve the cookies via JavaScript through the XmlHttpRequest Object, what is the point of Http-Only?
Consider this scenario:
I find an avenue to inject JavaScript code into the page.
Jeff loads the page and my malicious JavaScript modifies his cookie to match mine.
Jeff submits a stellar answer to your question.
Because he submits it with my cookie data instead of his, the answer will become mine.
You vote up "my" stellar answer.
My real account gets the point.
With HTTP-Only cookies, the second step would be impossible, thereby defeating my XSS attempt.
Edit 4: Sorry, I meant that you could send the XMLHttpRequest to the StackOverflow domain, and then save the result of getAllResponseHeaders() to a string, regex out the cookie, and then post that to an external domain. It appears that Wikipedia and ha.ckers concur with me on this one, but I would love be re-educated...
That's correct. You can still session hijack that way. It does significantly thin the herd of people who can successfully execute even that XSS hack against you though.
However, if you go back to my example scenario, you can see where HTTP-Only does successfully cut off the XSS attacks which rely on modifying the client's cookies (not uncommon).
It boils down to the fact that a) no single improvement will solve all vulnerabilities and b) no system will ever be completely secure. HTTP-Only is a useful tool in shoring up against XSS.
Similarly, even though the cross domain restriction on XmlHttpRequest isn't 100% successful in preventing all XSS exploits, you'd still never dream of removing the restriction.
Yes, they are a viable option for an Ajax based site. Authentication cookies aren't for manipulation by scripts, but are simply included by the browser on all HTTP requests made to the server.
Scripts don't need to worry about what the session cookie says - as long as you are authenticated, then any requests to the server initiated by either a user or the script will include the appropriate cookies. The fact that the scripts cannot themselves know the content of the cookies doesn't matter.
For any cookies that are used for purposes other than authentication, these can be set without the HTTP only flag, if you want script to be able to modify or read these. You can pick and choose which cookies should be HTTP only, so for example anything non-sensitive like UI preferences (sort order, collapse left hand pane or not) can be shared in cookies with the scripts.
I really like the HTTP only cookies - it's one of those proprietary browser extensions that was a really neat idea.
Not necessarily, it depends what you want to do. Could you elaborate a bit? AJAX doesn't need access to cookies to work, it can make requests on its own to extract information, the page request that the AJAX call makes could access the cookie data & pass that back to the calling script without Javascript having to directly access the cookies
As clarification - from the server's perspective, the page that is requested by an AJAX request is essentially no different to a standard HTTP get request done by the user clicking on a link. All the normal request properties: user-agent, ip, session, cookies, etc. are passed to the server.
There's a bit more to this.
Ajax doesn't strictly require cookies, but they can be useful as other posters have mentioned. Marking a cookie HTTPOnly to hide it from scripts only partially works, because not all browsers support it, but also because there are common workarounds.
It's odd that the XMLHTTPresponse headers are giving the cookie, technically the server doesn't have to return the cookie with the response. Once it's set on the client, it stays set until it expires. Though there are schemes in which the cookie is changed with every request to prevent re-use. So you may be able to avoid that workaround by changing the server to not provide the cookie on the XMLHTTP responses.
In general though, I think HTTPOnly should be used with some caution. There are cross site scripting attacks where an attacker arranges for a user to submit an ajax-like request originating from another site, using simple post forms, without the use of XMLHTTP, and your browser's still-active cookie would authenticate the request.
If you want to be sure that an AJAX request is authenticated, the request itself AND the HTTP headers need to contain the cookie. Eg through the use of scripts or unique hidden inputs. HTTPOnly would hinder that.
Usually the interesting reason to want HTTPOnly is to prevent third-party content included on your webpage from stealing cookies. But there are many interesting reasons to be very cautious about including third-party content, and filter it aggressively.
Cookies are automatically handled by the browser when you make an AJAX call, so there's no need for your Javascript to mess around with cookies.
Therefore I am assuming JavaScript needs access to your cookies.
All HTTP requests from your browser transmit your cookie information for the site in question. JavaScript can both set and read cookies. Cookies are not by definition required for Ajax applications, but they are required for most web applications to maintain user state.
The formal answer to your question as phrased - "Does JavaScript need access to cookies if AJAX is used?" - is therefore "no". Think of enhanced search fields that use Ajax requests to provide auto-suggest options, for example. There is no need of cookie information in that case.
No, the page that the AJAX call requests has access to cookies too & that's what checks whether you're logged in.
You can do other authentication with the Javascript, but I wouldn't trust it, I always prefer putting any sort of authentication checking in the back-end.
Yes, cookies are very useful for Ajax.
Putting the authentication in the request URL is bad practice. There was a news item last week about getting the authentication tokens in the URL's from the google cache.
No, there is no way to prevent attacks. Older browsers still allow trivial access to cookies via javascript. You can bypass http only, etc. Whatever you come up with can be gotten around given enough effort. The trick is to make it too much effort to be worthwhile.
If you want to make your site more secure (there is no perfect security) you could use an authentication cookie that expires. Then, if the cookie is stolen, the attacker must use it before it expires. If they don't then you have a good indication there's suspicious activity on that account. The shorter the time window the better for security but the more load it puts on your server generating and maintaining keys.

Resources