4.7. Server-Side Sessions#

When users interact with a website, the server needs a way to remember their identity across multiple requests. Since HTTP is stateless, web servers use sessions to track users.

A server-side session is a record stored on the server that contains at minimum:

  • user identifier

  • unique session identifier

Sessions allow users to interact with a website without having to provide their username and password with every request.

Server-side sessions are implemented by:

  • recording the session on the server

  • the browser retaining a session token as a cookie

4.7.1. Establishing a Server-Side Session#

The procedure to establish a server-side session is:

  1. The client (browser) sends a login request with username and password

  2. The server creates a new session record in its database

  3. The server sends a response back with a cookie containing the session identifier

For example the cookie header in the response might look like:

Set-Cookie: session_id=23409qwenoasd; Path=/; HttpOnly; Secure; Max-Age=86400

where the session_id is a random and unique identifier.

4.7.2. Maintaining a Server-Side Session#

On every subsequent request, the client sends the session identifier cookie to the server.

For example the header for subsequent responses might look like:

GET /dashboard HTTP/1.1
Host: example.com
Cookie: session_id=abc123

When the server receives a request containing a session identifier it:

  1. Queries the database for a session with a matching session identifier

  2. Checks that the session has not expired

  3. Returns a response for the logged in user

Demo: Server-Side Session and Login

Note

This tutorial demonstrates a simple way to implement server-side sessions with Flask. Run it like a normal Flask app.

The page should only allow users to log in with the following credentials:

username: admin password: password123

../../_images/session_loop.gif

Note

Once the cookie expires users are automatically logged out. You can see this by waiting for the session time to expire and then refreshing the page. Users should also be able to log out by clicking Logout. You can reduce the expiry time of the session from 1 hour to test it. For example to set it to 10 seconds use timedelta(seconds=10).

Models

In addition to the User model we’ve been using so far, we’re adding a model to hold the Session details in the database.

The session model fields are:

  • id - the unique identifier of the session, which the browser will use as a cookie value later

  • user_id - a foreign key to the associated user

  • active - whether the session is active, used to log out the user

  • expires_at - the final expiration date of the session

Warning

In the real world the id used for the session should be a random string that is hard to guess.

Login

The login process follows the steps:

  1. Get the credentials from the POST-ed form data

  2. Search the database for a matching user

  3. Create a new session in the database

  4. Return a response that sets a cookie in the user’s browser to store the session id

Dashboard

When /dashboard is requested:

  1. The value of the session_id cookie is collected

  2. The database is searched for a corresponding and active session exists in the database

  3. The expiration date of the session is checked

  4. The user details are retrieved from the database and the dashboard template is rendered into a response

Logout

When the user logs out they request /logout which then:

  1. Sets the session to inactive

  2. Sets the remaining time of the session_id cookie to 0, thereby causing the browser to destroy its copy as the time immediately passes.

Download and run the tutorial.

TUTORIAL_server-side_session_and_login.zip