0
0
Djangoframework~10 mins

DRF authentication (Token, JWT) in Django - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - DRF authentication (Token, JWT)
Client sends login request
Server verifies credentials
If valid
Generate Token or JWT
Send JWT to client
Send Token to client
Client stores token/JWT
Client sends requests with token/JWT
Server checks token/JWT validity
If valid
Allow access
Else deny access
This flow shows how a client logs in, receives a token or JWT, and uses it to access protected resources by sending it with requests.
Execution Sample
Django
from rest_framework.authtoken.models import Token
from rest_framework_simplejwt.tokens import RefreshToken
from django.contrib.auth import authenticate

# Token creation example
user = authenticate(username='user', password='pass')
if user:
    token, created = Token.objects.get_or_create(user=user)
    token_key = token.key

# JWT creation example
refresh = RefreshToken.for_user(user)
access_token = str(refresh.access_token)
This code shows how DRF creates a Token or JWT after user authentication.
Execution Table
StepActionInputOutputNotes
1Client sends login requestusername='user', password='pass'Request receivedClient initiates login
2Server verifies credentialsusername='user', password='pass'User object if validAuthentication check
3Generate TokenUser objectToken stringDRF Token created
4Generate JWTUser objectJWT access and refresh tokensJWT tokens created
5Send Token/JWT to clientToken or JWTToken/JWT sent in responseClient receives tokens
6Client stores token/JWTToken/JWTStored in client storageReady for future requests
7Client sends request with token/JWTToken/JWT in headerRequest received with tokenAuthentication header included
8Server checks token/JWT validityToken/JWTValid or invalidToken verified
9If valid, allow accessValid tokenProtected resource dataAccess granted
10If invalid, deny accessInvalid token401 UnauthorizedAccess denied
💡 Execution stops after access is granted or denied based on token validity.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7After Step 8Final
userNoneUser object if validUser objectUser objectUser objectUser objectUser objectUser objectUser object
tokenNoneNoneToken stringToken stringToken stringToken stringToken stringToken stringToken string
jwt_accessNoneNoneNoneJWT access tokenJWT access tokenJWT access tokenJWT access tokenJWT access tokenJWT access token
jwt_refreshNoneNoneNoneJWT refresh tokenJWT refresh tokenJWT refresh tokenJWT refresh tokenJWT refresh tokenJWT refresh token
request_tokenNoneNoneNoneNoneNoneToken/JWT storedToken/JWT sent with requestToken/JWT validatedAccess granted or denied
Key Moments - 3 Insights
Why do we generate both access and refresh tokens in JWT?
Access tokens are short-lived for security; refresh tokens allow getting new access tokens without logging in again. See execution_table rows 4 and 5.
What happens if the token sent by the client is invalid or expired?
The server denies access and returns 401 Unauthorized, as shown in execution_table row 10.
Is the token created at login or on every request?
Token or JWT is created once at login (rows 3 and 4), then sent with each request (row 7) for validation.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at Step 3?
AToken string
BJWT access token
CUser object
D401 Unauthorized
💡 Hint
Check the 'Output' column for Step 3 in the execution_table.
At which step does the client send the token or JWT with a request?
AStep 2
BStep 5
CStep 7
DStep 9
💡 Hint
Look for 'Client sends request with token/JWT' in the execution_table.
If the token is invalid, what is the server's response according to the execution_table?
AProtected resource data
B401 Unauthorized
CToken string
DUser object
💡 Hint
Check the 'Output' column for Step 10 in the execution_table.
Concept Snapshot
DRF Authentication with Token and JWT:
- Client logs in sending credentials.
- Server verifies and creates Token or JWT.
- Token/JWT sent back to client.
- Client stores and sends token with requests.
- Server validates token to allow or deny access.
- JWT uses access and refresh tokens for security.
Full Transcript
This visual execution trace shows how Django REST Framework (DRF) handles authentication using Token and JWT methods. First, the client sends a login request with username and password. The server checks these credentials. If valid, the server creates either a Token or JWT (which includes access and refresh tokens). These tokens are sent back to the client, who stores them securely. For future requests, the client includes the token or JWT in the request headers. The server then validates the token. If the token is valid, the server grants access to protected resources. If invalid or expired, the server denies access with a 401 Unauthorized response. This process ensures secure, stateless authentication for API access.