This project demonstrates how to implement session-based authentication in a FastAPI application. It provides a basic framework for user login, logout, and protected routes using server-side sessions.
- User Login: Authenticates existing users and establishes a session.
- Protected Routes: Restricts access to certain endpoints to authenticated users only.
- Session Management: Uses server-side sessions to maintain user state.
- Logout Functionality: Allows users to terminate their active session.
- Python 3.7+
uv(Python package installer)
-
Clone the repository:
git clone https://github.com/phiponatchi/fastapi-session-auth.git cd fastapi-session-auth -
Create a virtual environment and activate it:
uv venv
-
Install the dependencies:
uv sync
To start the FastAPI application, run the following command:
uv run fastapi run main.pyThe application will be accessible at http://127.0.0.1:8000.
GET /profile: Get Authenticated user profile (simple welcome message).POST /login: Log in an existing user (test user:username=user, password=password).POST /logout: Log out the current user.
├── main.py # Main FastAPI application file
├── dto.py # Pydantic models for request data
├── auth.py # Authentication logic (hashing, session management)
├── db.py # Database mockup and operations (e.g., python dict as db)
├── pyproject.toml. # Project dependencies
└── README.md # Project documentation
Contributions are welcome! Please feel free to open issues or submit pull requests.
This project is licensed under the MIT License.