Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
DRF Authentication with Token and JWT
📖 Scenario: You are building a simple Django REST API for a book collection app. You want to secure the API so only logged-in users can access their books. You will set up two common authentication methods: Token Authentication and JWT Authentication.
🎯 Goal: Set up Django REST Framework authentication using Token Authentication and JWT Authentication. You will create the initial project setup, configure authentication settings, implement token and JWT authentication, and complete the API views to require authentication.
📋 What You'll Learn
Create a Django project and app with Django REST Framework installed
Set up Token Authentication with DRF's built-in token system
Configure JWT Authentication using the 'djangorestframework-simplejwt' package
Protect API views so only authenticated users can access them
💡 Why This Matters
🌍 Real World
APIs often need secure authentication to protect user data. Token and JWT authentication are common methods used in real-world web applications.
💼 Career
Understanding how to implement and configure authentication in Django REST Framework is a valuable skill for backend developers working on secure APIs.
Progress0 / 4 steps
1
Create initial Django project and app
Create a Django project named bookproject and an app named books. In books/models.py, create a model called Book with fields title (CharField, max_length=100) and author (CharField, max_length=100).
Django
Hint
Use django-admin startproject bookproject and python manage.py startapp books to create the project and app. Then define the Book model in books/models.py.
2
Configure Token Authentication in settings
In bookproject/settings.py, add rest_framework and rest_framework.authtoken to INSTALLED_APPS. Then add a REST_FRAMEWORK setting with 'DEFAULT_AUTHENTICATION_CLASSES' set to include 'rest_framework.authentication.TokenAuthentication'.
Django
Hint
Modify INSTALLED_APPS to include the required apps. Then add the REST_FRAMEWORK dictionary with the authentication class.
3
Add JWT Authentication configuration
Install djangorestframework-simplejwt package. In bookproject/settings.py, import timedelta from datetime. Add SimpleJWT authentication to REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES']. Also add a SIMPLE_JWT dictionary with ACCESS_TOKEN_LIFETIME set to 5 minutes and REFRESH_TOKEN_LIFETIME set to 1 day.
Django
Hint
Use pip install djangorestframework-simplejwt to install the package. Then update REST_FRAMEWORK and add SIMPLE_JWT settings as shown.
4
Protect API views with authentication
In books/views.py, create a viewset BookViewSet that uses ModelViewSet for the Book model. Add permission_classes with IsAuthenticated to require authentication. In books/urls.py, register the viewset with a router under the path books/. Include these URLs in the main bookproject/urls.py.
Django
Hint
Use ModelViewSet and IsAuthenticated permission to protect the API. Register the viewset with a router and include the URLs in the main project.
Practice
(1/5)
1. What is the main difference between TokenAuthentication and JWTAuthentication in Django REST Framework?
easy
A. TokenAuthentication uses simple tokens stored on the server; JWTAuthentication uses encoded tokens with expiry.
B. TokenAuthentication requires username and password every request; JWTAuthentication does not.
C. TokenAuthentication encrypts tokens; JWTAuthentication sends tokens as plain text.
D. TokenAuthentication is only for web apps; JWTAuthentication is only for mobile apps.
Solution
Step 1: Understand TokenAuthentication
TokenAuthentication uses a simple token string stored on the server and sent by the client to identify the user.
Step 2: Understand JWTAuthentication
JWTAuthentication uses JSON Web Tokens that are encoded, include expiry info, and do not require server storage.
Final Answer:
TokenAuthentication uses simple tokens stored on the server; JWTAuthentication uses encoded tokens with expiry. -> Option A
Quick Check:
Token vs JWT difference = D [OK]
Hint: Token is simple stored string; JWT is encoded with expiry [OK]
Common Mistakes:
Thinking JWT tokens are stored on the server
Confusing token encryption with encoding
Assuming TokenAuthentication requires password every request
2. Which of the following is the correct way to add TokenAuthentication to a Django REST Framework view?
easy
A. authentication_classes = ["rest_framework.authentication.TokenAuthentication"]
B. authentication_classes = [TokenAuthentication]
C. authentication_classes = [rest_framework.authentication.TokenAuthentication]
D. authentication_classes = [TokenAuthentication()]
Solution
Step 1: Recall how to import and use authentication classes
Authentication classes must be imported and instantiated, so use TokenAuthentication() not just the class name or string.
Step 2: Check syntax for authentication_classes
It expects a list of authentication class instances, so the correct syntax is [TokenAuthentication()] with parentheses.
Final Answer:
authentication_classes = [TokenAuthentication()] -> Option D
Quick Check:
Use class instances in list = A [OK]
Hint: Use class instances with parentheses in authentication_classes list [OK]
Common Mistakes:
Using strings instead of class instances
Forgetting parentheses after class name
Not importing TokenAuthentication before use
3. Given this Django REST Framework view snippet using JWTAuthentication, what will happen if the token is expired?
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.views import APIView
from rest_framework.response import Response
class MyView(APIView):
authentication_classes = [JWTAuthentication()]
def get(self, request):
return Response({"user": str(request.user)})
medium
A. The request will succeed but request.user will be None.
B. The request will succeed and return the user even if token expired.
C. The request will be denied with a 401 Unauthorized error.
D. The server will crash with an exception.
Solution
Step 1: Understand JWTAuthentication behavior on expired tokens
JWTAuthentication checks token expiry and rejects requests with expired tokens by raising an authentication error.
Step 2: Effect on the APIView request
When token is expired, the request is denied with a 401 Unauthorized response automatically by DRF.
Final Answer:
The request will be denied with a 401 Unauthorized error. -> Option C
Quick Check:
Expired JWT causes 401 error = B [OK]
Hint: Expired JWT tokens cause 401 Unauthorized error [OK]
Common Mistakes:
Assuming expired token returns user as None
Thinking expired token lets request pass
Expecting server crash on expired token
4. You wrote this code to enable TokenAuthentication but your API always returns 403 Forbidden. What is the likely mistake?
from rest_framework.authentication import TokenAuthentication
class MyView(APIView):
authentication_classes = [TokenAuthentication]
def get(self, request):
return Response({"message": "Hello"})
medium
A. Forgot to add parentheses after TokenAuthentication in authentication_classes.
B. TokenAuthentication is not imported correctly.
C. The get method should be named post.
D. authentication_classes should be a tuple, not a list.
Solution
Step 1: Check authentication_classes syntax
authentication_classes must contain instances, so TokenAuthentication() with parentheses, not the class itself.
Step 2: Effect of missing parentheses
Without parentheses, DRF does not recognize the authentication class properly, causing 403 Forbidden errors.
Final Answer:
Forgot to add parentheses after TokenAuthentication in authentication_classes. -> Option A
Quick Check:
Use TokenAuthentication() not TokenAuthentication = C [OK]
Hint: Always instantiate authentication classes with () [OK]
Common Mistakes:
Using class name without parentheses
Confusing 403 with 401 errors
Changing method name unnecessarily
5. You want to protect an API endpoint so only users with a valid JWT token can access it, and you want tokens to expire after 5 minutes. Which settings and code changes should you apply?
hard
A. Set TOKEN_EXPIRE_TIME = 300 in settings and use TokenAuthentication() in authentication_classes.
B. Set SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'] = timedelta(minutes=5) in settings and use JWTAuthentication() in authentication_classes.
C. Use JWTAuthentication() in authentication_classes and set JWT_EXPIRATION_DELTA = 5 in settings.
D. Use TokenAuthentication() and manually check token age in the view.
Solution
Step 1: Configure JWT token expiry
In Django REST Framework Simple JWT, set ACCESS_TOKEN_LIFETIME to 5 minutes using timedelta in settings.
Step 2: Use JWTAuthentication in the view
Set authentication_classes = [JWTAuthentication()] to enforce JWT token authentication on the endpoint.
Final Answer:
Set SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'] = timedelta(minutes=5) in settings and use JWTAuthentication() in authentication_classes. -> Option B
Quick Check:
JWT expiry + JWTAuthentication = A [OK]
Hint: Set ACCESS_TOKEN_LIFETIME and use JWTAuthentication() [OK]
Common Mistakes:
Using TokenAuthentication instead of JWTAuthentication