In the context of web applications, a session is a mechanism to maintain information about the user’s activity across multiple requests and multiple pages. It helps the server to remember who the user is and what they are doing during their visit.
One of the common uses of the session is user authentication. It identifies the user and keeps track of what they are doing.
Here is how session-based authentication works.
Suppose you are trying to access a protected page of a web application from your browser. You will be greeted with a login page where you have to provide your username and password. This page is like a door lock protecting the application, and your username and password are the key to open the door.
When you provide your username and password, the application checks your credentials. If the username and password match, it creates a session for you. It stores the session in the session storage and returns a reference of the session to the browser. This session is often called a session ID and only the server can identify it. The browser saves it in a cookie.
For any subsequent request to the server, the browser sends the session reference from its cookie with the request. The server takes the session reference/ID, searches for the session in its session storage. If it finds a valid session, it allows the user to do further tasks that they are permitted to do.
If the server does not find any session or finds the session is invalid, it stops doing any further processing of the request and redirects the user to the login page or, in some cases, notifies the user that they are not authorized to access the protected resource. The whole process is illustrated in the image below.
Another important note is that sessions do not stay forever. They usually have only a 30-minute lifetime, though this is configurable.