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:- Create the Login API.
- Create and store user sessions.
- Send the session ID as an HTTP cookie.
- Authenticate users using the session cookie.
- Protect API endpoints.
- 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
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
Verify
After restarting the application, a new SQLite database namedsession_auth.db should be created with the following tables.
Session Table
Expected Outcome
At the end of this task, you should have:- A
Usermodel. - A
Sessionmodel. - Request models for registration and login.
- Database tables created automatically.
Task 3 - Implement Password Hashing
Goal
Implement password hashing and password verification usingbcrypt.
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.
Run the Application
Test the API
Open the Swagger UI.Verify
Open theuser table in the SQLite database.
The password should be stored as a hashed value similar to:
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.
How It Works
- Receive the username and password.
- Retrieve the user from the database.
- Verify the password.
- Generate a unique session ID.
- Store the session in the database.
- Send the session ID as an HTTP cookie.
- Return a success response.
Run the Application
Test the API
Open the Swagger UI.Verify
After a successful login:- A new record should be created in the
sessiontable. - A cookie named
session_idshould 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
- Read the
session_idcookie. - Find the corresponding session in the database.
- Retrieve the associated user.
- Return the authenticated user.
- 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.
How It Works
The/public endpoint is accessible to everyone.
The /protected endpoint depends on the authenticate_user() dependency. Before executing the endpoint, FastAPI:
- Reads the
session_idcookie. - Validates the session.
- Retrieves the authenticated user.
- Executes the endpoint only if the session is valid.
Run the Application
Test the APIs
Open the Swagger UI.Public Endpoint
Call:Protected Endpoint
- Register a new user.
- Login using the
/loginendpoint. - Call:
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.
How It Works
- Read the
session_idcookie. - Find the corresponding session in the database.
- Delete the session.
- Remove the session cookie from the client.
- Return a success response.
Run the Application
Test the API
Open the Swagger UI.Verify
After logging out:- The corresponding record should be removed from the
sessiontable. - The
session_idcookie 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.