
When you build a web application, authentication is one of the first things you need to think about. You might have a dashboard, an admin panel, a user profile page, or an API that should only be accessible to logged-in users. Whatever you're building, you need a reliable way to verify who is making each request.
One common approach is JWT authentication.
JWT stands for JSON Web Token. It allows your application to authenticate users without storing a traditional server-side session for every logged-in user. Instead, after a successful login, the server generates a signed token that the client sends with subsequent requests.
In this guide, we'll build JWT authentication in Flask from scratch. We'll create registration and login endpoints, generate tokens, protect routes, and handle token expiration. We'll also cover common mistakes and security practices you should follow in real projects.
Let's get started.
What Is JWT Authentication?
A JSON Web Token is a compact token used to transfer information between two parties. In authentication systems, a server commonly issues a JWT after verifying a user's credentials.
The client then includes that token when requesting protected resources.
A JWT typically contains three parts:
header.payload.signatureEach part has a specific purpose:
Header: Contains metadata about the token, including its signing algorithm.
Payload: Contains claims, such as the user's identifier and token expiration time.
Signature: Helps the server verify that the token hasn't been modified.
For example, a JWT payload might look like this:
{
"sub": "user_123",
"role": "user",
"exp": 1924992000
}This is only an example. The exp value represents a Unix timestamp, and the token is valid only until that time.
One important thing to understand is that a signed JWT is not automatically encrypted. Its payload can generally be decoded by anyone who has the token. Never put passwords, API secrets, or other sensitive information inside it.
How Does JWT Authentication Work?
Before writing code, let's understand the complete authentication flow.
Imagine you're building a Flask API with a React or Next.js frontend.
The process works like this:
A user registers with an email and password.
The Flask backend validates the registration data and stores the user's password as a hash.
The user submits their credentials to the login endpoint.
Flask verifies the email and password.
If the credentials are correct, Flask generates a signed JWT.
The client stores the token according to the application's security requirements.
The client sends the token with requests to protected endpoints.
Flask verifies the token's signature and expiration before returning protected data.
For example, a protected request might look like this:
GET /api/profile
Authorization: Bearer YOUR_ACCESS_TOKENThe Bearer prefix indicates that the client is sending a bearer token in the authorization header.
If the token is valid, the server processes the request. If the token is missing, invalid, or expired, the server rejects it.
Step 1: Create a Flask Project
First, make sure Python is installed on your machine.
You can check the installed version with:
python --versionDepending on your system, you might need to use python3 instead.
Create a project directory:
mkdir flask-jwt-auth
cd flask-jwt-authNow create a virtual environment:
python -m venv venvActivate it on macOS or Linux:
source venv/bin/activateOn Windows:
venv\Scripts\activateA virtual environment keeps your project's Python dependencies separate from other Python projects.
Next, install the required packages:
pip install Flask Flask-JWT-Extended Flask-SQLAlchemy Flask-Bcrypt python-dotenvHere's what each package does:
Package | Purpose |
|---|---|
Flask | Creates the web application and API routes |
Flask-JWT-Extended | Handles JWT creation and verification |
Flask-SQLAlchemy | Provides database integration through SQLAlchemy |
Flask-Bcrypt | Hashes passwords securely |
python-dotenv | Loads environment variables from a |
We'll use SQLite for this tutorial because it doesn't require a separate database server. You can use PostgreSQL or MySQL in a production application with the appropriate database driver and configuration.
Step 2: Create the Project Structure
Let's keep the project simple and organized.
Create the following files:
flask-jwt-auth/
│
├── app.py
├── models.py
├── .env
├── .gitignore
├── requirements.txt
└── venv/The responsibilities are straightforward:
app.pycontains the Flask application, authentication routes, and protected endpoints.models.pycontains the database model..envstores local environment variables..gitignoreprevents sensitive or unnecessary files from being committed.requirements.txtlists the Python dependencies.
You can start with this structure and split routes, services, and configuration into separate modules as the application grows.
Step 3: Configure Environment Variables
Create a .env file in your project root:
JWT_SECRET_KEY=replace-this-with-a-long-random-secret
DATABASE_URL=sqlite:///users.dbThe JWT secret is used to sign tokens. Anyone who obtains this secret may be able to create tokens your application accepts, so keep it private.
For local development, you can generate a random secret using Python:
python -c "import secrets; print(secrets.token_urlsafe(48))"Copy the generated value into your .env file.
Do not commit the real secret to GitHub. In production, configure secrets through your hosting platform's environment-variable or secrets-management system.
Create a .gitignore file:
venv/
__pycache__/
.env
instance/
*.dbThe database file is ignored here because this tutorial uses a local SQLite database. If your project intentionally tracks a database file, adjust this rule accordingly.
Step 4: Create the User Model
A user model represents the users stored in your database.
Open models.py and add:
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
db = SQLAlchemy()
bcrypt = Bcrypt()
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(
db.String(80),
unique=True,
nullable=False
)
email = db.Column(
db.String(120),
unique=True,
nullable=False
)
password_hash = db.Column(
db.String(255),
nullable=False
)
def set_password(self, password):
self.password_hash = bcrypt.generate_password_hash(
password
).decode("utf-8")
def check_password(self, password):
return bcrypt.check_password_hash(
self.password_hash,
password
)Let's understand what's happening.
Why Do We Store a Password Hash?
When a user registers, you should never store their password as plain text.
For example, avoid storing this:
password = mypassword123Instead, store a password hash generated by a suitable password-hashing algorithm.
The set_password() method hashes the supplied password, while check_password() verifies a login attempt against the stored hash.
This means the original password isn't stored in the database.
Also notice that the model uses password_hash, not password. This makes it clearer that the database contains a hash rather than the original password.
Step 5: Initialize Flask and JWT
Now open app.py.
Add the following code:
import os
from dotenv import load_dotenv
from flask import Flask, jsonify, request
from flask_jwt_extended import (
JWTManager,
create_access_token,
get_jwt_identity,
jwt_required,
)
from datetime import timedelta
from models import db, bcrypt, User
load_dotenv()
app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("JWT_SECRET_KEY")
app.config["JWT_SECRET_KEY"] = os.getenv("JWT_SECRET_KEY")
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv(
"DATABASE_URL",
"sqlite:///users.db"
)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(minutes=15)
if not app.config["JWT_SECRET_KEY"]:
raise RuntimeError("JWT_SECRET_KEY must be configured.")
db.init_app(app)
bcrypt.init_app(app)
jwt = JWTManager(app)
with app.app_context():
db.create_all()Here's what the important parts do:
load_dotenv()loads local environment variables.JWT_SECRET_KEYprovides the signing secret for access tokens.JWT_ACCESS_TOKEN_EXPIRESsets access-token expiration to 15 minutes.db.init_app(app)connects SQLAlchemy to the Flask application.bcrypt.init_app(app)initializes password hashing.JWTManager(app)configures JWT handling.db.create_all()creates the database tables that don't already exist.
For a small tutorial, db.create_all() is convenient. For a production application, use database migrations so schema changes can be tracked and applied safely.
The SECRET_KEY setting is included for Flask's own signing features. The JWT extension uses the separate JWT_SECRET_KEY setting for JWT signing.
Step 6: Create the Registration Endpoint
A registration endpoint allows new users to create accounts.
Add this route to app.py:
@app.route("/api/register", methods=["POST"])
def register():
data = request.get_json(silent=True) or {}
username = data.get("username", "").strip()
email = data.get("email", "").strip().lower()
password = data.get("password", "")
if not username or not email or not password:
return jsonify({
"message": "Username, email, and password are required."
}), 400
if len(password) < 12:
return jsonify({
"message": "Password must contain at least 12 characters."
}), 400
existing_user = User.query.filter(
(User.username == username) |
(User.email == email)
).first()
if existing_user:
return jsonify({
"message": "Username or email is already registered."
}), 409
user = User(
username=username,
email=email
)
user.set_password(password)
db.session.add(user)
db.session.commit()
return jsonify({
"message": "User registered successfully."
}), 201This endpoint performs several important checks:
It reads the JSON request body.
It verifies that the required fields are present.
It checks the minimum password length.
It checks whether the username or email is already registered.
It hashes the password and saves the new user.
It returns a success response.
The example uses a minimum length of 12 characters as a basic starting point. A production authentication system should also enforce a sensible password policy, validate email addresses, limit registration attempts, and consider password-breach screening.
Test the Registration Endpoint
You can test the endpoint using Postman or another API client.
Send a POST request to:
http://127.0.0.1:5000/api/registerChoose a JSON request body:
{
"username": "manjeet",
"email": "manjeet@example.com",
"password": "MyStrongPassword123!"
}If the registration succeeds, the response should look like this:
{
"message": "User registered successfully."
}The response status code should be 201 Created.
Remember to use a test email address and a non-sensitive password when experimenting.
Step 7: Create the Login Endpoint
Now let's implement login.
When a user logs in, Flask will find their account, verify the password, and generate a JWT access token.
Add this route:
@app.route("/api/login", methods=["POST"])
def login():
data = request.get_json(silent=True) or {}
email = data.get("email", "").strip().lower()
password = data.get("password", "")
if not email or not password:
return jsonify({
"message": "Email and password are required."
}), 400
user = User.query.filter_by(email=email).first()
if not user or not user.check_password(password):
return jsonify({
"message": "Invalid email or password."
}), 401
access_token = create_access_token(
identity=str(user.id),
additional_claims={
"role": "user"
}
)
return jsonify({
"message": "Login successful.",
"access_token": access_token,
"token_type": "Bearer"
}), 200Let's break down the most important part:
access_token = create_access_token(
identity=str(user.id),
additional_claims={
"role": "user"
}
)The create_access_token() function generates a signed JWT.
We use the user's database ID as the token identity. Converting it to a string keeps it compatible with the identity format expected by current Flask-JWT-Extended configurations.
The additional role claim is included as an example of token metadata. In a real application, assign roles based on trusted database records rather than allowing users to choose their own roles.
Also remember that JWT claims are readable by anyone who possesses the token. They are not a safe place for secrets.
Test the Login Endpoint
Send a POST request to:
http://127.0.0.1:5000/api/loginRequest body:
{
"email": "manjeet@example.com",
"password": "MyStrongPassword123!"
}A successful response will contain an access token:
{
"message": "Login successful.",
"access_token": "YOUR_GENERATED_JWT",
"token_type": "Bearer"
}The token shown above is a placeholder. Your application will generate a different token when you log in.
Keep the returned token for the next step.
Step 8: Create a Protected Route
So far, users can register and log in. But how do we prevent unauthenticated users from accessing private information?
This is where @jwt_required() comes in.
Add a protected profile endpoint:
@app.route("/api/profile", methods=["GET"])
@jwt_required()
def profile():
user_id = get_jwt_identity()
user = db.session.get(User, int(user_id))
if not user:
return jsonify({
"message": "User not found."
}), 404
return jsonify({
"id": user.id,
"username": user.username,
"email": user.email
}), 200The @jwt_required() decorator verifies that the request contains a valid JWT access token.
Then this line retrieves the identity stored in the verified token:
user_id = get_jwt_identity()We use that identity to find the user in the database.
Notice that the endpoint returns only selected user fields. It doesn't return the password hash or other unnecessary internal data.
Important: A valid token proves that the token was issued and hasn't been tampered with. It doesn't automatically mean the user still has permission to access every resource. You must check ownership and authorization rules for sensitive operations.
How to Call the Protected Endpoint
Send a GET request to:
http://127.0.0.1:5000/api/profileIn Postman, open the Authorization tab and select Bearer Token. Paste the access token returned by the login endpoint.
Alternatively, send this header manually:
Authorization: Bearer YOUR_GENERATED_JWTIf the token is valid, the response will contain the user's profile.
If you don't send a token, Flask-JWT-Extended rejects the request.
Step 9: Add Token Error Handling
A production API should return consistent responses when authentication fails.
Flask-JWT-Extended provides callbacks for handling missing, invalid, and expired tokens.
Add these handlers to app.py:
@jwt.unauthorized_loader
def missing_token(reason):
return jsonify({
"message": "Authorization token is required."
}), 401
@jwt.invalid_token_loader
def invalid_token(reason):
return jsonify({
"message": "Invalid authorization token."
}), 401
@jwt.expired_token_loader
def expired_token(jwt_header, jwt_payload):
return jsonify({
"message": "Access token has expired."
}), 401These callbacks improve the consistency of your API responses.
For example, an expired token might produce:
{
"message": "Access token has expired."
}with an HTTP 401 Unauthorized status.
Don't return stack traces, secret values, or unnecessary internal details to clients.
Step 10: Complete Flask JWT Authentication Code
At this point, your app.py should contain the imports, configuration, registration endpoint, login endpoint, protected profile endpoint, error handlers, and development server entry point.
Add the following at the bottom of the file:
if __name__ == "__main__":
app.run(debug=True)Your final project structure remains:
flask-jwt-auth/
├── app.py
├── models.py
├── .env
├── .gitignore
├── requirements.txt
└── venv/Create the dependency file:
pip freeze > requirements.txtStart the Flask development server:
python app.pyThe application should start on:
http://127.0.0.1:5000You can now test the full flow:
Register a user.
Log in with the registered credentials.
Copy the returned access token.
Call the profile endpoint with the token.
Try the profile endpoint without a token.
Wait for the access token to expire and test it again.
This gives you a basic working JWT authentication API in Flask.
Step 11: How to Use JWT Authentication With React or Next.js
If you're building a frontend with React or Next.js, the client needs to send the access token when calling protected Flask endpoints.
For example, using fetch():
const token = "YOUR_ACCESS_TOKEN";
const response = await fetch(
"http://127.0.0.1:5000/api/profile",
{
method: "GET",
headers: {
Authorization: `Bearer ${token}`,
},
}
);
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || "Request failed");
}
console.log(data);In a real application, don't hardcode the token like this. The example simply demonstrates how to send the authorization header.
Where Should You Store the Token?
Token storage is an important security decision.
Two common approaches are:
1. HttpOnly cookies
The server stores the token in a cookie configured with appropriate flags, such as HttpOnly, Secure, and SameSite.
JavaScript cannot read an HttpOnly cookie. This reduces the risk of token theft through certain cross-site scripting attacks. However, cookie-based authentication requires careful CSRF protection and appropriate cookie settings.
2. Browser storage
Some applications store tokens in memory or browser storage. This can be convenient, but JavaScript-accessible storage can expose tokens if an attacker manages to execute malicious scripts on the page.
Avoid treating localStorage as automatically secure. If you use it, understand the XSS risks and apply strong frontend security practices.
For applications that need longer-lived login sessions, consider a short-lived access token plus a carefully designed refresh-token flow. Refresh tokens need their own storage, rotation, revocation, and reuse-detection strategy.
There isn't one storage option that is best for every application. The right choice depends on your architecture, threat model, and deployment requirements.
Step 12: Access Tokens vs Refresh Tokens
You may have noticed that our access token expires after 15 minutes.
Short expiration times reduce the period during which a stolen access token can be used. However, they can also mean users need to authenticate more frequently unless your application supports refreshing tokens.
This is where refresh tokens come in.
Feature | Access Token | Refresh Token |
|---|---|---|
Main purpose | Access protected APIs | Obtain new access tokens |
Typical lifetime | Short | Longer |
Sent with normal API requests | Yes | Usually no |
Security requirements | Validate on each protected request | Store and manage carefully |
Revocation strategy | Often limited unless additional controls are used | Commonly tracked and revocable |
A refresh-token flow usually works like this:
The user logs in successfully.
The server issues an access token and a refresh token.
The client uses the access token for protected API requests.
When the access token expires, the client sends the refresh token to a dedicated endpoint.
The server verifies the refresh token and issues a new access token.
The server rotates or revokes refresh tokens according to the application's security policy.
Flask-JWT-Extended supports refresh tokens, but this tutorial doesn't implement a refresh endpoint. A production implementation should include refresh-token expiration, revocation or rotation, secure storage, and reuse detection where appropriate.
Step 13: Protect Admin Routes With Roles
Authentication and authorization are related, but they solve different problems.
Authentication: Who is making the request?
Authorization: Is that user allowed to perform this action?
For example, a normal user may be allowed to view their profile but not delete another user's account.
You can use JWT claims as one part of your authorization logic. However, sensitive permissions may need to be checked against current database records so that role changes take effect promptly.
Here's a basic example of an admin-only route:
from flask_jwt_extended import get_jwt
@app.route("/api/admin", methods=["GET"])
@jwt_required()
def admin_dashboard():
claims = get_jwt()
if claims.get("role") != "admin":
return jsonify({
"message": "Admin access required."
}), 403
return jsonify({
"message": "Welcome to the admin dashboard."
}), 200The code checks the role claim in the verified JWT.
Our login example assigns every user the role user, so this endpoint will reject those tokens. To support administrators, your application needs a trusted way to assign admin privileges and issue appropriate tokens.
For higher-security applications, check current permissions in the database or another trusted authorization service rather than relying entirely on a potentially outdated role claim.
Never let a client supply an arbitrary role during registration or login.
Common JWT Authentication Errors in Flask
Let's look at a few problems you might encounter while building this application.
1. Missing Authorization Header
You might receive a 401 Unauthorized response when calling a protected route.
Check that your request contains the header:
Authorization: Bearer YOUR_GENERATED_JWTMake sure you're sending the actual token returned by the login endpoint, not the placeholder text.
2. Signature Verification Failed
This error can occur if the token was signed with a different secret from the one your application currently uses.
Check the following:
Is
JWT_SECRET_KEYconfigured correctly?Did you restart the server after changing the secret?
Are you using a token from another environment?
Was the token modified or copied incorrectly?
Changing the signing secret invalidates tokens signed with the previous secret.
3. Token Has Expired
If an access token expires, the API should reject it.
Log in again to get a new token. If your application supports refresh tokens, use the refresh flow instead.
Don't simply disable expiration to avoid dealing with this error.
4. User Already Exists
The registration endpoint returns 409 Conflict if the username or email is already registered.
Try a different email address, or build a separate account-recovery or login flow for existing users.
In production, enforce uniqueness at the database level and handle uniqueness conflicts cleanly to avoid race conditions between simultaneous registration requests.
5. Database Table Does Not Exist
If you change the database model or configuration, your local database may not match the code.
For this tutorial, db.create_all() creates missing tables. It does not update existing tables to reflect every model change.
Use migrations when you need to change an existing database schema safely.
6. JWT Library Import Errors
If Python reports that flask_jwt_extended cannot be imported, make sure you installed the package in the active virtual environment:
pip install Flask-JWT-ExtendedYou can also check the installed package:
pip show Flask-JWT-ExtendedIf the error persists, confirm that the virtual environment is activated and that you're running the same Python interpreter in which you installed the package.
JWT Authentication Security Best Practices
The examples above are suitable for learning the basic flow. Before using JWT authentication in a real application, pay attention to security.
Use Strong Secrets
Generate a long, random signing secret. Never use predictable values such as secret123 or commit production secrets to a public repository.
For systems requiring more advanced key management, consider asymmetric signing algorithms and a proper key-rotation strategy.
Always Use HTTPS in Production
HTTPS protects tokens while they're being transmitted between the client and server.
Without transport encryption, attackers on an insecure network may be able to intercept bearer tokens and use them.
Set Token Expiration
Access tokens should generally have a limited lifetime appropriate to the sensitivity of the application.
Short-lived tokens reduce the window in which stolen tokens can be used, although expiration alone doesn't provide immediate revocation.
Never Store Plain-Text Passwords
Use a password-hashing algorithm designed for password storage. Flask-Bcrypt provides a practical option for this example.
Never log passwords or include them in JWT claims.
Validate Input
Validate request bodies before using them. Check required fields, lengths, formats, and acceptable values.
For production applications, use a validation library or a clearly defined validation layer to keep these checks consistent.
Add Rate Limiting
Login and registration endpoints can be targets for brute-force attacks and automated abuse.
Use rate limiting, monitoring, and suitable account-protection mechanisms. Avoid relying on a simple in-memory counter when deploying multiple application instances.
Implement Authorization Checks
A valid token doesn't automatically grant access to every resource.
Check resource ownership and user permissions before allowing actions such as updating accounts, viewing private records, or deleting data.
Plan for Revocation
JWTs are often validated without looking up a server-side session on every request. That can make immediate revocation more complicated than with traditional sessions.
Depending on your requirements, you may need a token blocklist, short-lived access tokens, refresh-token rotation, user-token versioning, or another revocation mechanism.
Keep Dependencies Updated
Authentication libraries are security-sensitive dependencies. Keep them updated, review release notes, and test changes before deploying them to production.
JWT vs Session-Based Authentication
JWT is popular for API authentication, but it isn't the only option.
Traditional server-side sessions are still a good choice for many applications.
Feature | JWT Authentication | Session-Based Authentication |
|---|---|---|
Authentication state | Stored in a signed token | Stored on the server |
Client sends | Usually a bearer token or cookie | Usually a session cookie |
Server-side session storage | Not required for basic JWT validation | Generally required |
Revocation | Requires additional planning for immediate invalidation | Often straightforward by invalidating the session |
Scaling | Can simplify stateless API authentication | May need shared session storage |
Best fit | APIs, distributed services, certain mobile applications | Traditional web applications and many browser-based apps |
The important point is that JWT isn't automatically more secure or faster than session authentication.
If you're building a traditional server-rendered application, sessions may be simpler. If you're building an API consumed by multiple clients, JWTs may be a good fit.
Choose based on your application's requirements rather than using JWT simply because it's popular.
Frequently Asked Questions
1. What is JWT authentication in Flask?
JWT authentication in Flask is a way to verify users with JSON Web Tokens. After a successful login, Flask issues a signed token that the client sends with requests to protected endpoints.
2. Which library is best for JWT authentication in Flask?
Flask-JWT-Extended is a popular option for Flask applications. It supports creating access tokens, protecting routes, verifying tokens, handling expiration, and implementing refresh-token workflows.
3. Is JWT authentication secure?
JWT can be used securely when implemented correctly. Use strong signing keys, HTTPS, suitable token expiration, secure token storage, and proper authorization checks. Remember that a signed JWT is not necessarily encrypted.
4. Where should I store JWT tokens in a React application?
The answer depends on your application's architecture and threat model. HttpOnly cookies can reduce exposure to JavaScript-based token theft, but cookie-based authentication requires CSRF protections. Browser storage is convenient but can expose tokens to XSS attacks.
5. What happens when a JWT expires?
The server rejects the expired token. The user can log in again or use a properly implemented refresh-token flow to obtain a new access token.
6. Can I use JWT authentication with Flask and React?
Yes. Flask can expose authentication endpoints, while React sends the access token with requests to protected APIs. Configure CORS appropriately if your frontend and backend use different origins.
7. Should I use JWT or sessions?
Use the approach that fits your application. JWT can work well for distributed APIs, while sessions can be simpler for traditional web applications and offer straightforward server-side invalidation.
8. Does JWT replace password hashing?
No. JWT handles token-based authentication after credentials are verified. Password hashing protects stored passwords. They solve different security problems and are commonly used together.
Final Thoughts
JWT authentication is a useful skill for anyone building APIs with Flask. Once you understand how tokens are generated, verified, and used to protect routes, you can apply the same concepts to larger applications.
In this tutorial, we built a basic authentication flow with Flask, SQLAlchemy, Flask-Bcrypt, and Flask-JWT-Extended. We created registration and login endpoints, generated access tokens, protected a profile route, handled common token errors, and discussed authorization and security.
If you're coming from Node.js and Express, the concepts will feel familiar. The main difference is how Flask organizes routes, extensions, database models, and request handling.
Start with the basic implementation, test each endpoint, and then add features such as refresh tokens, password reset, email verification, rate limiting, and role-based access control as your application grows.
The goal isn't just to make authentication work. It's to make sure it works safely.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


