Authentication helps check who a user is before giving access. Token and JWT are ways to do this safely in Django REST Framework.
DRF authentication (Token, JWT) in Django
from rest_framework.authentication import TokenAuthentication from rest_framework_simplejwt.authentication import JWTAuthentication # In your Django settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # For Token auth 'rest_framework_simplejwt.authentication.JWTAuthentication', # For JWT auth ], }
TokenAuthentication uses a simple token string to identify users.
JWTAuthentication uses JSON Web Tokens that include encoded user info and expiry.
# Token Authentication example from rest_framework.authentication import TokenAuthentication from rest_framework.views import APIView from rest_framework.response import Response class MyView(APIView): authentication_classes = [TokenAuthentication] def get(self, request): return Response({'message': 'Hello, token user!'})
# JWT Authentication example 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({'message': 'Hello, JWT user!'})
This API view requires a valid token to access. It greets the logged-in user by name.
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated class HelloTokenView(APIView): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def get(self, request): username = request.user.username return Response({'message': f'Hello, {username}! You are authenticated with Token.'})
Tokens must be sent in the HTTP header as Authorization: Token <token> for TokenAuthentication.
JWT tokens are sent as Authorization: Bearer <jwt_token>.
Always keep tokens secret and use HTTPS to protect them in transit.
Token and JWT are ways to check who is using your API safely.
TokenAuthentication uses simple tokens; JWTAuthentication uses encoded tokens with expiry.
Use authentication classes in your views or settings to protect your API endpoints.
Practice
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 AQuick Check:
Token vs JWT difference = D [OK]
- Thinking JWT tokens are stored on the server
- Confusing token encryption with encoding
- Assuming TokenAuthentication requires password every request
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 DQuick Check:
Use class instances in list = A [OK]
- Using strings instead of class instances
- Forgetting parentheses after class name
- Not importing TokenAuthentication before use
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)})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 CQuick Check:
Expired JWT causes 401 error = B [OK]
- Assuming expired token returns user as None
- Thinking expired token lets request pass
- Expecting server crash on expired token
from rest_framework.authentication import TokenAuthentication
class MyView(APIView):
authentication_classes = [TokenAuthentication]
def get(self, request):
return Response({"message": "Hello"})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 AQuick Check:
Use TokenAuthentication() not TokenAuthentication = C [OK]
- Using class name without parentheses
- Confusing 403 with 401 errors
- Changing method name unnecessarily
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 BQuick Check:
JWT expiry + JWTAuthentication = A [OK]
- Using TokenAuthentication instead of JWTAuthentication
- Setting wrong expiry setting names
- Trying to manually check token expiry in views
Ready to prove it?
Pass the test and this pattern moves unknown
