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
JWT Authentication0%
Study Materials
REST API Development with DjangoProgress 0%
1.1REST Principles1.2HTTP Methods Overview1.3Status Codes
4.1Token Authentication4.2JWT Authentication4.3Custom Permissions
HomeTutorialsREST API Development with DjangoJWT Authentication
Custom Permissions

JWT Authentication

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

While standard database tokens require an SQL query on every single HTTP request, JSON Web Tokens (JWT) provide stateless, cryptographically signed authentication. The enterprise standard library for JWT in Django is djangorestframework-simplejwt. It implements short-lived Access Tokens and long-lived Refresh Tokens with built-in token rotation.


1. Dual-Token JWT Architecture

11. Client POST /api/token/ (credentials) ──► Returns: { access: "...", refresh: "..." }
22. Client calls API with: Authorization: Bearer <access_token> (Valid for 5-15 mins)
33. Access token expires (401 Unauthorized)
44. Client POST /api/token/refresh/ (refresh_token) ──► Returns fresh <access_token>

2. Installation & Setup

1pip install djangorestframework-simplejwt

Configure JWTAuthentication in settings.py:

1# config/settings.py
2REST_FRAMEWORK = {
3 "DEFAULT_AUTHENTICATION_CLASSES": [
4 "rest_framework_simplejwt.authentication.JWTAuthentication",
5 ],
6}

3. Registering JWT Endpoints in urls.py

1# config/urls.py
2from django.urls import path
3from rest_framework_simplejwt.views import (
4 TokenObtainPairView,
5 TokenRefreshView,
6 TokenVerifyView,
7)
8 
9urlpatterns = [
10 # 1. Login / Obtain token pair
11 path("api/token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),
12 # 2. Silent refresh
13 path("api/token/refresh/", TokenRefreshView.as_view(), name="token_refresh"),
14 # 3. Verify validity
15 path("api/token/verify/", TokenVerifyView.as_view(), name="token_verify"),
16]

4. Customizing JWT Lifetimes & Rotation Settings

1# config/settings.py
2from datetime import timedelta
3 
4SIMPLE_JWT = {
5 "ACCESS_TOKEN_LIFETIME": timedelta(minutes=15), # Short-lived access
6 "REFRESH_TOKEN_LIFETIME": timedelta(days=7), # Long-lived refresh
7 "ROTATE_REFRESH_TOKENS": True, # Issue NEW refresh token on refresh
8 "BLACKLIST_AFTER_ROTATION": True, # Invalidate old refresh token!
9 "UPDATE_LAST_LOGIN": True,
10
11 "ALGORITHM": "HS256",
12 "SIGNING_KEY": SECRET_KEY,
13 "AUTH_HEADER_TYPES": ("Bearer",), # Expects: Authorization: Bearer <token>
14 "USER_ID_FIELD": "id",
15 "USER_ID_CLAIM": "user_id",
16}

5. Adding Custom Claims to Tokens

By default, JWTs only include user_id. You can embed custom claims (like email, role, or tenant_id) to avoid database lookups on client frontends:

1# accounts/tokens.py
2from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
3from rest_framework_simplejwt.views import TokenObtainPairView
4 
5class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
6 @classmethod
7 def get_token(cls, user):
8 token = super().get_token(user)
9 
10 # Inject custom claims into the signed JWT payload:
11 token["email"] = user.email
12 token["role"] = getattr(user, "role", "viewer")
13 token["organization_id"] = str(user.organization.id) if getattr(user, "organization", None) else None
14 
15 return token
16 
17class CustomTokenObtainPairView(TokenObtainPairView):
18 serializer_class = CustomTokenObtainPairSerializer

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What header format does SimpleJWT expect for authenticated requests?
Question 2
What security advantage does ROTATE_REFRESH_TOKENS and BLACKLIST_AFTER_ROTATION provide?
Question 3
Why are Access Tokens configured with short lifetimes (e.g. 5 to 15 minutes)?
Question 4
What does the TokenRefreshView endpoint (/api/token/refresh/) do?
Question 5
What information is contained in the signature of a JSON Web Token?
Next Lesson

Custom Permissions

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

Related Lessons

Previous LessonNext Lesson
Token AuthenticationCustom Permissions

Practice Quiz

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

Mentor-Led Practical Training

Master REST API Development with Django 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