MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Stateless JWT Authentication with Flask-JWT-Extended0%
Study Materials
FlaskProgress 0%
1.1What is Flask & WSGI Architecture1.2Virtual Environments & First Flask Application1.3Flask CLI & Environment Configuration
8.1Building JSON APIs with jsonify & Status Codes8.2Data Serialization & Validation with Marshmallow8.3Stateless JWT Authentication with Flask-JWT-Extended
HomeTutorialsFlaskStateless JWT Authentication with Flask-JWT-Extended
Background Tasks with Celery and Redis

Stateless JWT Authentication with Flask-JWT-Extended

Beginner12 min read•Updated: 2026-09-16•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

While cookie-based sessions (like Flask-Login) work seamlessly for traditional server-rendered websites, modern mobile apps and Single Page Applications (Next.js, React) require stateless authentication. Storing session IDs in cookies across cross-domain mobile applications triggers CORS restrictions and cross-site cookie blocking.

JSON Web Tokens (JWT) provide cryptographically signed, stateless authentication tokens. The Flask-JWT-Extended extension is the premier library for implementing JWT authentication in Flask.


1. How JWT Authentication Works

A JWT is an encoded, cryptographically signed token containing three base64-encoded segments:

1[ Header (algorithm & token type) ].[ Payload (claims & user ID) ].[ Signature (HMAC-SHA256) ]

2. Installing and Configuring Flask-JWT-Extended

1pip install flask-jwt-extended

In app.py:

1import os
2from datetime import timedelta
3from flask import Flask
4from flask_jwt_extended import JWTManager
5 
6app = Flask(__name__)
7 
8# Essential: Strong secret key used to sign JWT signatures
9app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY", "jwt-super-secret-key-prod")
10app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(minutes=15)
11app.config["JWT_REFRESH_TOKEN_EXPIRES"] = timedelta(days=30)
12 
13jwt = JWTManager(app)

3. Login Endpoint & Issuing Tokens

1from flask import request, jsonify
2from flask_jwt_extended import create_access_token, create_refresh_token
3from models import User
4 
5@app.route("/api/v1/auth/login", methods=["POST"])
6def api_login():
7 data = request.get_json() or {}
8 username = data.get("username")
9 password = data.get("password")
10 
11 user = User.query.filter_by(username=username).first()
12 if not user or not user.verify_password(password):
13 return jsonify({"error": "Invalid credentials"}), 401
14 
15 # Identity can be user ID or username
16 # Additional claims store roles or permissions directly in token!
17 access_token = create_access_token(
18 identity=str(user.id),
19 additional_claims={"role": user.role}
20 )
21 refresh_token = create_refresh_token(identity=str(user.id))
22 
23 return jsonify({
24 "access_token": access_token,
25 "refresh_token": refresh_token,
26 "token_type": "Bearer"
27 }), 200

4. Protecting Endpoints with @jwt_required()

Restricting an endpoint requires decorating the view with @jwt_required():

1from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt
2 
3@app.route("/api/v1/user/profile", methods=["GET"])
4@jwt_required()
5def get_user_profile():
6 # Extracts the user ID encoded in the verified JWT
7 user_id = get_jwt_identity()
8 user = User.query.get_or_404(int(user_id))
9
10 # Access custom claims
11 claims = get_jwt()
12 user_role = claims.get("role")
13 
14 return jsonify({
15 "id": user.id,
16 "username": user.username,
17 "role": user_role
18 }), 200

5. Refreshing Access Tokens

When an access token expires (401 Token has expired), clients submit their refresh token to obtain a fresh access token without re-prompting for credentials:

1@app.route("/api/v1/auth/refresh", methods=["POST"])
2@jwt_required(refresh=True)
3def refresh_token():
4 # Only accepts a valid Refresh Token
5 current_user_id = get_jwt_identity()
6 new_access_token = create_access_token(identity=current_user_id)
7
8 return jsonify({"access_token": new_access_token}), 200

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
In which HTTP header does a client typically transmit a JWT token?
Question 2
What is the primary purpose of separating tokens into an Access Token and a Refresh Token?
Question 3
What decorator protects endpoints requiring a valid access token in Flask-JWT-Extended?
Question 4
How do you extract the user identity encoded in the verified JWT inside a route?
Question 5
What setting must be passed to @jwt_required() on an endpoint designed specifically to issue new access tokens?
Next Lesson

Background Tasks with Celery and Redis

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Data Serialization & Validation with MarshmallowBackground Tasks with Celery and Redis

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Flask with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext