Bird
Raised Fist0
Djangoframework~20 mins

DRF authentication (Token, JWT) in Django - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

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
Challenge - 5 Problems
🎖️
DRF Authentication Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output of this DRF view with TokenAuthentication?

Given the following Django REST Framework view using TokenAuthentication, what will be the HTTP status code if a request is made without any token?

Django
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 SampleView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'message': 'Success'})
A401 Unauthorized error
B200 OK with {'message': 'Success'}
C403 Forbidden error
D500 Internal Server Error
Attempts:
2 left
💡 Hint

Think about what happens when authentication credentials are missing.

📝 Syntax
intermediate
2:00remaining
Which option correctly configures JWT authentication in DRF settings?

In Django REST Framework, you want to enable JWT authentication using SimpleJWT. Which of the following REST_FRAMEWORK settings is correct?

A
"""
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.JWTAuthentication',
    ],
}
"""
B
"""
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.JWTAuthentication',
    ],
}
"""
C
"""
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}
"""
D
"""
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.TokenAuthentication',
    ],
}
"""
Attempts:
2 left
💡 Hint

Check the full import path for JWTAuthentication in SimpleJWT.

state_output
advanced
2:00remaining
What is the value of request.user after JWT authentication?

In a DRF view using JWT authentication, after a valid JWT token is provided, what is the type of request.user?

Django
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):
        user_type = type(request.user).__name__
        return Response({'user_type': user_type})
A"TokenUser"
B"User"
C"AnonymousUser"
D"CustomUser"
Attempts:
2 left
💡 Hint

Think about what Django sets as the user after successful authentication.

🔧 Debug
advanced
2:00remaining
Why does this DRF view raise an error with TokenAuthentication?

Consider this DRF view using TokenAuthentication. It raises an error when a request with a valid token is made. What is the cause?

Django
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 DebugView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        token_key = request.auth.key
        return Response({'token': token_key})
A'request.auth' is None, so accessing 'key' raises AttributeError
B'request.auth' is a Token object, but 'key' attribute is misspelled
C'request.auth' is a Token object, but 'key' attribute is private
D'request.auth' is a string, so 'key' attribute does not exist
Attempts:
2 left
💡 Hint

Check the type of request.auth when using TokenAuthentication.

🧠 Conceptual
expert
2:00remaining
Which statement correctly describes JWT token refresh behavior in DRF SimpleJWT?

In Django REST Framework using SimpleJWT, which statement about the token refresh endpoint is true?

AThe refresh token can be used multiple times until it expires to get new access tokens.
BThe refresh token can only be used once; after refresh, it becomes invalid.
CThe refresh token automatically renews itself on every access token request.
DThe refresh token is the same as the access token but with a longer expiry.
Attempts:
2 left
💡 Hint

Think about how refresh tokens work in JWT authentication.

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

  1. Step 1: Understand TokenAuthentication

    TokenAuthentication uses a simple token string stored on the server and sent by the client to identify the user.
  2. Step 2: Understand JWTAuthentication

    JWTAuthentication uses JSON Web Tokens that are encoded, include expiry info, and do not require server storage.
  3. Final Answer:

    TokenAuthentication uses simple tokens stored on the server; JWTAuthentication uses encoded tokens with expiry. -> Option A
  4. 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

  1. 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.
  2. Step 2: Check syntax for authentication_classes

    It expects a list of authentication class instances, so the correct syntax is [TokenAuthentication()] with parentheses.
  3. Final Answer:

    authentication_classes = [TokenAuthentication()] -> Option D
  4. 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

  1. Step 1: Understand JWTAuthentication behavior on expired tokens

    JWTAuthentication checks token expiry and rejects requests with expired tokens by raising an authentication error.
  2. Step 2: Effect on the APIView request

    When token is expired, the request is denied with a 401 Unauthorized response automatically by DRF.
  3. Final Answer:

    The request will be denied with a 401 Unauthorized error. -> Option C
  4. 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

  1. Step 1: Check authentication_classes syntax

    authentication_classes must contain instances, so TokenAuthentication() with parentheses, not the class itself.
  2. Step 2: Effect of missing parentheses

    Without parentheses, DRF does not recognize the authentication class properly, causing 403 Forbidden errors.
  3. Final Answer:

    Forgot to add parentheses after TokenAuthentication in authentication_classes. -> Option A
  4. 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

  1. Step 1: Configure JWT token expiry

    In Django REST Framework Simple JWT, set ACCESS_TOKEN_LIFETIME to 5 minutes using timedelta in settings.
  2. Step 2: Use JWTAuthentication in the view

    Set authentication_classes = [JWTAuthentication()] to enforce JWT token authentication on the endpoint.
  3. Final Answer:

    Set SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'] = timedelta(minutes=5) in settings and use JWTAuthentication() in authentication_classes. -> Option B
  4. Quick Check:

    JWT expiry + JWTAuthentication = A [OK]
Hint: Set ACCESS_TOKEN_LIFETIME and use JWTAuthentication() [OK]
Common Mistakes:
  • Using TokenAuthentication instead of JWTAuthentication
  • Setting wrong expiry setting names
  • Trying to manually check token expiry in views