What are sessions? How do they work?

Viewed 212300

I am just beginning to start learning web application development, using python. I am coming across the terms 'cookies' and 'sessions'. I understand cookies in that they store some info in a key value pair on the browser. But I have a little confusion regarding sessions, in a session too we store data in a cookie on the user's browser.

For example - I login using username='rasmus' and password='default'. In such a case the data will be posted to the server which is supposed to check and log me in if authenticated. However during the entire process the server also generates a session ID which will be stored in a cookie on my browser. Now the server also stores this session ID in its file system or datastore.

But based on just the session ID, how would it be able to know my username during my subsequent traversal through the site? Does it store the data on the server as a dict where the key would be a session ID and details like username, email etc. be the values?

I am getting quite confused here. Need help.

6 Answers

Session is broad technical term which can be used to refer to a state which is stored either on server side using in-memory cache or on the client side using cookie, local storage or session storage.

There is nothing specific on the browser or server that is called session. Session is a kind of data which represents a user session on web. And that data can be stored on server or client.

And how it stored and shared is another topic. But the brief is when a user is logged in, the server creates a session data and generates a session ID. The session Id is sent back to user in custom header or set-cookie header which takes care of automatically storing it on user's browser. And then when next time the user revisits, the session ID is sent along the request and server check if there is existing session by that ID and processes accordingly.

You can store whatever you want in an session but the the main purpose is to remember the the user (browser) who have previously visit your site whether it's about login, shopping cart, or other activities.

And that's why it also important to protect the session ID from being intercepted by a hacker who will use it to identify himself as an another user.

By reading about Cookie, you will get the idea of session: (https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)

Excerpt from MDN:

Cookies are mainly used for three purposes:

Session management

    Logins, shopping carts, game scores, or anything else the server should remember
Personalization

    User preferences, themes, and other settings
Tracking

    Recording and analyzing user behavior
Related