Bird
Raised Fist0
Djangoframework~15 mins

DRF authentication (Token, JWT) in Django - Deep Dive

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
Overview - DRF authentication (Token, JWT)
What is it?
DRF authentication means checking who a user is when they try to use a Django REST Framework API. Token and JWT are two ways to prove a user's identity by giving them a secret code. Token authentication gives a simple secret key, while JWT gives a special code that carries user info safely. These methods help keep APIs safe by making sure only real users can access data.
Why it matters
Without authentication, anyone could use an API and see or change private data. This would be like leaving your house unlocked for strangers. Token and JWT authentication protect APIs by making users prove who they are. This keeps data safe and builds trust in apps that use APIs.
Where it fits
Before learning DRF authentication, you should know basic Django and how REST APIs work. After this, you can learn about permissions, user roles, and securing APIs with HTTPS. Later, you might explore advanced topics like OAuth or social login.
Mental Model
Core Idea
Authentication in DRF is like giving a secret badge (token or JWT) to users so the API knows who they are without asking for a password every time.
Think of it like...
Imagine going to a concert where you get a wristband at the entrance. This wristband lets you move around freely without showing your ticket again. Token and JWT work like that wristband for APIs.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│   Client App  │──────▶│  API Server   │──────▶│  Protected    │
│ (User logs in)│       │(Checks token) │       │  Resources    │
└───────────────┘       └───────────────┘       └───────────────┘
        │                      ▲                       ▲
        │                      │                       │
        │        Token or JWT  │                       │
        └──────────────────────┘                       │
                                                       │
                                               Access granted if valid
Build-Up - 7 Steps
1
FoundationWhat is DRF Authentication
🤔
Concept: Understanding the basic idea of authentication in Django REST Framework.
Authentication means checking who a user is before letting them use an API. DRF provides ways to do this automatically. When a user logs in, the API gives them a secret code to prove their identity later.
Result
You know that authentication is about proving user identity to protect API access.
Understanding authentication is the first step to securing any API and controlling who can see or change data.
2
FoundationToken Authentication Basics
🤔
Concept: Learning how simple token authentication works in DRF.
Token authentication gives each user a unique secret token string. The user sends this token with every API request in the header. The server checks the token to confirm the user’s identity.
Result
Users can access the API by sending their token, no need to send username and password every time.
Knowing that tokens are like secret keys helps you understand how stateless authentication works.
3
IntermediateJWT Authentication Explained
🤔Before reading on: Do you think JWT is just a random token or does it carry user info? Commit to your answer.
Concept: JWT (JSON Web Token) is a special token that carries encoded user info and can be verified without database lookup.
JWT contains three parts: header, payload, and signature. The payload holds user data like ID and expiration time. The signature ensures the token wasn’t changed. The server can check JWT validity without storing tokens.
Result
JWT lets the server trust the token’s info and verify users quickly without extra database calls.
Understanding JWT’s self-contained nature explains why it scales well for large apps.
4
IntermediateHow to Use Token Authentication in DRF
🤔Before reading on: Do you think token authentication requires storing tokens in the database? Commit to your answer.
Concept: Token authentication in DRF uses a database table to store tokens linked to users.
You install 'rest_framework.authtoken', run migrations to create token table, then assign tokens to users. Clients send tokens in 'Authorization: Token ' header. The server checks the token in the database to authenticate.
Result
API requests with valid tokens succeed; invalid or missing tokens get denied.
Knowing token storage is important for managing token lifecycle and revoking access.
5
IntermediateHow to Use JWT Authentication in DRF
🤔Before reading on: Do you think JWT tokens need to be stored on the server? Commit to your answer.
Concept: JWT tokens are not stored on the server; they are verified using a secret key.
You install a JWT package like 'djangorestframework-simplejwt', configure secret keys, and set JWT as the authentication class. Clients get JWT tokens by logging in, then send them in 'Authorization: Bearer ' header. The server verifies signature and expiration.
Result
JWT tokens allow stateless authentication with embedded user info and expiration.
Understanding stateless JWT means you can build scalable APIs without token database overhead.
6
AdvancedToken vs JWT: Pros and Cons
🤔Before reading on: Which do you think is better for scaling APIs, token or JWT? Commit to your answer.
Concept: Comparing token and JWT authentication to understand when to use each.
Token authentication is simple and easy to revoke but requires database lookups. JWT is stateless and scales well but revoking tokens is harder. JWT carries user info, so it can reduce database calls but needs careful secret management.
Result
You can choose the right authentication method based on app needs like scalability and security.
Knowing tradeoffs helps avoid common mistakes like using JWT without token revocation strategy.
7
ExpertSecurity Pitfalls and Best Practices
🤔Before reading on: Do you think storing JWT tokens in localStorage is safe? Commit to your answer.
Concept: Understanding common security risks and how to avoid them in DRF authentication.
Storing JWT in localStorage exposes tokens to cross-site scripting attacks. Using HttpOnly cookies is safer. Always use HTTPS to protect tokens in transit. Implement token expiration and refresh tokens to limit damage from stolen tokens. For token authentication, revoke tokens on logout or suspicious activity.
Result
Your API authentication is more secure and less vulnerable to attacks.
Knowing these security details prevents serious breaches and protects user data.
Under the Hood
Token authentication stores a token string linked to a user in the database. When a request comes, DRF looks up the token to find the user. JWT authentication encodes user info and expiration in a signed token. The server verifies the signature using a secret key without database lookup. This makes JWT stateless and faster for large scale.
Why designed this way?
Token authentication was designed for simplicity and easy revocation by storing tokens server-side. JWT was created to solve scaling issues by making tokens self-contained and verifiable without server storage. The tradeoff is complexity in managing token security and revocation.
┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Client sends  │──────▶│ Server checks │──────▶│ Database token│
│ Token header  │       │ token in DB   │       │ table for user│
└───────────────┘       └───────────────┘       └───────────────┘

JWT flow:

┌───────────────┐       ┌───────────────┐       ┌───────────────┐
│ Client sends  │──────▶│ Server verifies│       │ No DB lookup  │
│ JWT in header │       │ signature and │──────▶│ Uses secret key│
└───────────────┘       │ expiration    │       └───────────────┘
                        └───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does JWT require storing tokens in the database? Commit yes or no.
Common Belief:JWT tokens must be stored in the database like regular tokens.
Tap to reveal reality
Reality:JWT tokens are self-contained and verified using a secret key without any database storage.
Why it matters:Storing JWT tokens unnecessarily wastes resources and complicates scaling.
Quick: Is it safe to store JWT tokens in localStorage? Commit yes or no.
Common Belief:Storing JWT tokens in localStorage is safe and convenient for web apps.
Tap to reveal reality
Reality:localStorage is vulnerable to cross-site scripting attacks, risking token theft.
Why it matters:Token theft can lead to account hijacking and data breaches.
Quick: Does token authentication automatically expire tokens? Commit yes or no.
Common Belief:Token authentication tokens expire automatically after some time.
Tap to reveal reality
Reality:By default, DRF token authentication tokens do not expire unless you add extra logic.
Why it matters:Without expiration, stolen tokens can be used forever, risking security.
Quick: Can JWT tokens be revoked easily like token authentication? Commit yes or no.
Common Belief:JWT tokens can be revoked instantly like token authentication tokens.
Tap to reveal reality
Reality:JWT tokens are hard to revoke before expiration without extra infrastructure.
Why it matters:Failing to revoke JWT tokens can allow attackers to use stolen tokens longer.
Expert Zone
1
JWT tokens can carry custom claims to include user roles or permissions, reducing database calls but increasing token size.
2
Token authentication allows easy token revocation by deleting tokens from the database, which is harder with JWT without a blacklist system.
3
JWT signature verification depends on secret key security; rotating keys requires careful token invalidation strategies.
When NOT to use
Avoid JWT if your app needs instant token revocation or you cannot secure secret keys properly. Use token authentication or OAuth2 with refresh tokens instead. For very simple APIs with few users, token authentication is easier to implement and manage.
Production Patterns
In production, JWT is often used with short-lived access tokens and long-lived refresh tokens to balance security and usability. Token authentication is common in internal APIs or admin panels where token revocation is critical. Combining JWT with HTTPS, HttpOnly cookies, and CSRF protection is a common best practice.
Connections
OAuth2
builds-on
Understanding DRF token and JWT authentication helps grasp OAuth2 flows, which use tokens for delegated access with more complex rules.
HTTP Headers
same pattern
Both token and JWT authentication rely on sending secrets in HTTP headers, showing how headers carry important metadata in web communication.
Digital Signatures (Cryptography)
builds-on
JWT uses digital signatures to verify token integrity, connecting web authentication to cryptographic principles ensuring data trust.
Common Pitfalls
#1Sending JWT tokens in localStorage without protection.
Wrong approach:localStorage.setItem('token', jwtToken); // used directly in JavaScript
Correct approach:Set JWT token in HttpOnly, Secure cookie from server to prevent JavaScript access.
Root cause:Misunderstanding that localStorage is vulnerable to cross-site scripting attacks.
#2Assuming DRF token authentication tokens expire automatically.
Wrong approach:Using DRF token authentication without adding expiration logic, expecting tokens to expire.
Correct approach:Implement custom token expiration or switch to JWT which supports expiration by default.
Root cause:Confusing token authentication with JWT behavior regarding token lifetime.
#3Not verifying JWT signature properly on the server.
Wrong approach:Decoding JWT payload without checking signature or expiration.
Correct approach:Use JWT libraries that verify signature and expiration before trusting token data.
Root cause:Lack of understanding of JWT security model and risks of trusting unsigned tokens.
Key Takeaways
DRF authentication protects APIs by verifying user identity using tokens or JWTs.
Token authentication stores tokens server-side and is easy to revoke but requires database lookups.
JWT tokens are self-contained, signed, and stateless, making them scalable but harder to revoke.
Security best practices include using HTTPS, secure storage, token expiration, and careful secret management.
Choosing between token and JWT depends on app needs like scalability, security, and token management.

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