Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript read session cookies only

I am wondering if there is an existing trick to filter on the cookies. I need to get the session cookies only and to discard the other. The usual way to read cookies using Javascript is:

document.cookie

However this prints all the cookies, my goal here is to get the session cookies only. I know that unlike "normal" cookies a session cookie has an expiration date.

Does anyone have a code sample to achieve this session cookies extraction?

Best, Alexandre

like image 563
Alexandre Avatar asked Feb 15 '16 08:02

Alexandre


People also ask

How do I read session cookies?

The only reliable way to identify a session cookie is if you know its name (this is website-dependent of course, but isn't a problem if this is your website). Also, you have no way of knowing a cookie's expiration date from Javascript. Now document. cookie gives you all cookies as a semi-colon delimited string.

Can JavaScript only read http cookies?

An HttpOnly cookie cannot be accessed by client-side APIs, such as JavaScript. This restriction eliminates the threat of cookie theft via cross-site scripting (XSS). If the browser allowed you to access it then it would be a defect in the browser.

Can JavaScript read secure cookies?

Secure as in the cookie cannot be read by Javascript running in the browser — ie. document. cookie will not work.

What is session cookie in JavaScript?

Cookies are client-side files on a local computer that hold user information. Sessions are server-side files that contain user data. Cookies end on the lifetime set by the user. When the user quits the browser or logs out of the programmed, the session is over.


1 Answers

A "session cookie" is a normal cookie. It may (or may not) have an expiration date but nothing prevents other cookies to have an expiration date as well. The only reliable way to identify a session cookie is if you know its name (this is website-dependent of course, but isn't a problem if this is your website).

Also, you have no way of knowing a cookie's expiration date from Javascript.

Now document.cookie gives you all cookies as a semi-colon delimited string. You just need to break it down on semi-colons to retrieve the key-value pairs. So here's a sample code to look for a cookie given its name:

var getCookie = function(name) {
    var cookies = document.cookie.split(';');
    for(var i=0 ; i < cookies.length ; ++i) {
        var pair = cookies[i].trim().split('=');
        if(pair[0] == name)
            return pair[1];
    }
    return null;
};

If you don't know the session cookie's name you're out of luck. Period. You could maybe find clever heuristics to determine which one it is (based on the form of name and/or value), but nothing can tell you exactly for all websites with 100% confidence which cookie is the session cookie, and if there is one at all.

like image 61
Pikrass Avatar answered Sep 21 '22 00:09

Pikrass