Skip to main content
Instead of sending the username and password with every request, users will log in once. After successful authentication, the server will create a session and return a session cookie. The browser automatically sends this cookie with subsequent requests, allowing the server to identify the authenticated user.

What We Will Implement

  • Login using username and password.
  • Create a unique session for authenticated users.
  • Store the session on the server.
  • Send the session ID to the client as an HTTP cookie.
  • Authenticate users using the session cookie.
  • Protect API endpoints using session-based authentication.
  • Implement logout by destroying the user session.

Authentication Flow

Session-Based Authentication is a stateful authentication mechanism in which the server maintains authentication information for each logged-in user. After a successful login, the server creates a unique session, stores it, and sends a session identifier to the client as a cookie. For subsequent requests, the browser automatically sends the session cookie, allowing the server to identify the authenticated user.

Overall Flow

Components

Advantages

  • Users log in only once.
  • Username and password are not sent with every request.
  • Browsers automatically send cookies with each request.
  • Easy to implement for traditional web applications.
  • The server can immediately invalidate a session by deleting it.
  • Supports centralized session management.
  • Well suited for server-rendered applications.

Disadvantages

  • The server must maintain session state.
  • Requires additional storage for active sessions.
  • Less scalable in distributed or microservice architectures.
  • Session storage must be shared across multiple servers in load-balanced environments.
  • Cookies are primarily designed for browser-based applications.
  • Session expiration and cleanup must be managed by the server.

APIs

Implementation Plan

We will complete this implementation in the following tasks:
  1. Create the Login API.
  2. Create and store user sessions.
  3. Send the session ID as an HTTP cookie.
  4. Authenticate users using the session cookie.
  5. Protect API endpoints.
  6. Implement Logout by deleting the session.

Task 1 - Create the Project

Goal

Create a new FastAPI project for implementing Session-Based Authentication using SQLite.

Create the Project

Create the Project Structure

Create the required files. Windows
macOS / Linux

Update database.py

Update app.py

Run the Application

Verify

Open the following URLs:

Expected Outcome

At the end of this task, you should have:
  • A new FastAPI project.
  • A configured SQLite database.
  • A running FastAPI application.
  • The project ready for implementing session-based authentication.

Task 2 - Create the User and Session Models

Goal

Create the database models required for implementing session-based authentication.

Update models.py

Restart the application.

Verify

After restarting the application, a new SQLite database named session_auth.db should be created with the following tables.

Session Table

Expected Outcome

At the end of this task, you should have:
  • A User model.
  • A Session model.
  • Request models for registration and login.
  • Database tables created automatically.

Task 3 - Implement Password Hashing

Goal

Implement password hashing and password verification using bcrypt.

Update auth.py

Run the File

Expected Output

Why Hash Passwords?

Passwords should never be stored as plain text. Instead, only their hashed values are stored in the database. During authentication, the entered password is verified against the stored hash.

Expected Outcome

At the end of this task, you should have:
  • A reusable password hashing function.
  • A reusable password verification function.
  • A secure mechanism for storing user passwords.

Task 4 - Implement User Registration

Goal

Create an API to register new users by storing their username and hashed password in the database.

Update app.py

Import the required modules.
Implement the registration endpoint.

Run the Application

Test the API

Open the Swagger UI.
Call the registration endpoint.
Request Body

Verify

Open the user table in the SQLite database. The password should be stored as a hashed value similar to:
instead of

Expected Outcome

At the end of this task, you should have:
  • A working user registration API.
  • Duplicate username validation.
  • Passwords stored securely using hashing.

Task 5 - Implement Login and Create User Sessions

Goal

Authenticate users using their username and password. After successful authentication, create a new session for the user and store it in the database.

Update app.py

Import the required modules.
Implement the login endpoint.

How It Works

  1. Receive the username and password.
  2. Retrieve the user from the database.
  3. Verify the password.
  4. Generate a unique session ID.
  5. Store the session in the database.
  6. Send the session ID as an HTTP cookie.
  7. Return a success response.

Run the Application

Test the API

Open the Swagger UI.
Call:
Request Body

Verify

After a successful login:
  • A new record should be created in the session table.
  • A cookie named session_id should be returned in the response.

Expected Outcome

At the end of this task, you should have:
  • A working login API.
  • Username and password verification.
  • A unique session created for each successful login.
  • The session ID stored in the database.
  • The session ID sent to the client as an HTTP cookie.

Task 6 - Authenticate Users Using Session Cookies

Goal

Authenticate users using the session ID stored in the HTTP cookie.

Update auth.py

Add the following function.

How It Works

  1. Read the session_id cookie.
  2. Find the corresponding session in the database.
  3. Retrieve the associated user.
  4. Return the authenticated user.
  5. Return 401 Unauthorized if the session is invalid.

Authentication Flow

Expected Outcome

At the end of this task, you should have:
  • A reusable session authentication dependency.
  • Cookie-based authentication.
  • Session validation.
  • Retrieval of the authenticated user.

Task 7 - Create Public and Protected Endpoints

Goal

Create public and protected endpoints using session-based authentication.

Update app.py

Import the authentication dependency.
Add the following endpoints.

How It Works

The /public endpoint is accessible to everyone. The /protected endpoint depends on the authenticate_user() dependency. Before executing the endpoint, FastAPI:
  1. Reads the session_id cookie.
  2. Validates the session.
  3. Retrieves the authenticated user.
  4. Executes the endpoint only if the session is valid.

Run the Application

Test the APIs

Open the Swagger UI.

Public Endpoint

Call:
This endpoint is accessible without authentication.

Protected Endpoint

  1. Register a new user.
  2. Login using the /login endpoint.
  3. Call:
If a valid session cookie is present, the response will be:
If the session is missing or invalid, the response will be:

Authentication Flow

Expected Outcome

At the end of this task, you should have:
  • A public endpoint accessible to everyone.
  • A protected endpoint requiring a valid session.
  • A working implementation of session-based authentication.

Task 8 - Implement Logout

Goal

Log out the authenticated user by deleting the session from the database and removing the session cookie.

Update app.py

Import the required modules.
Implement the logout endpoint.

How It Works

  1. Read the session_id cookie.
  2. Find the corresponding session in the database.
  3. Delete the session.
  4. Remove the session cookie from the client.
  5. Return a success response.

Run the Application

Test the API

Open the Swagger UI.
Call:

Verify

After logging out:
  • The corresponding record should be removed from the session table.
  • The session_id cookie should be deleted.
  • Accessing the protected endpoint should return:

Session Lifecycle

Expected Outcome

At the end of this task, you should have:
  • A working logout API.
  • Server-side session invalidation.
  • Client-side cookie removal.
  • A complete session-based authentication system.