Here's a breakdown of each section:
1. User Registration
- Step 1: The user sends a
POST
request to the /auth/register
endpoint with their username and password. - Step 2: The Flask App checks the database to see if the user already exists.
- Step 3: If the user doesn't exist, the app saves the new user with a hashed password to the database.
- Step 4: A success message is returned to the user.
2. User Login
- Step 1: The user sends a
POST
request to /auth/login
with their credentials. - Step 2: The Flask App validates the credentials against the database.
- Step 3: If valid, the app generates a JWT access token.
- Step 4: The token is sent back to the user for future authentication.
3. Accessing a Protected Route
- Step 1: The user sends a
GET
request to /auth/protected
with the JWT token in the Authorization header. - Step 2: The app validates the token using the JWT service.
- Step 3: If the token is valid, the app retrieves the user's identity from the database.
- Step 4: A success response is returned to the user with a personalized message.
4. Invalid Access Attempt
- Step 1: If the user tries to access the protected route without a token or with an invalid token, the app validates the token.
- Step 2: The validation fails, and the app responds with a
401 Unauthorized
error message.
This guide provides a step-by-step tutorial on implementing JWT (JSON Web Token) Authentication and Authorization in a Python Flask application from scratch. You'll learn how to build a secure authentication system, allowing users to register, log in, and access protected resources based on their roles. The guide covers essential components like setting up a Flask project, integrating JWT, handling user roles, and securing routes. By the end, you'll have a robust foundation for building scalable, secure APIs for your web or mobile applications.
Step-by-Step Guide
1. Setting Up Your Flask Project
Install the required dependencies:
2. Create Project Structure
Organize your files as follows:
3. Configuring the Application
In config.py
, define the secret key for JWT:
4. Database Setup
In database.py
, initialize SQLAlchemy:
5. Create User Model
In models.py
, define the User
model:
6. Implement Routes
In routes.py
, define authentication and authorization logic:
7. Integrating Components
In app.py
, integrate everything:
8. Testing the Application
Register a User
Endpoint: POST /auth/register
Request Body:
Login a User
Endpoint: POST /auth/login
Request Body:
Response:
Access Protected Route
Endpoint: GET /auth/protected
Headers:
Response:
9. Secure Routes with Roles (Optional)
Extend the User
model to include roles and add role-based authorization checks. For example:
10. Secure the Application
- Use HTTPS in production.
- Rotate
JWT_SECRET_KEY
periodically. - Implement token expiration and refresh.