Django REST JWT Auth With Refresh
Implement JWT authentication with access and refresh tokens in Django REST Framework.
Code
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
@api_view(['POST'])
def login(request):
user = authenticate(request, **request.data)
if user:
refresh = RefreshToken.for_user(user)
return Response({
'access': str(refresh.access_token),
'refresh': str(refresh),
})
return Response({'error': 'invalid credentials'}, status=401)
@api_view(['GET'])
@permission_classes([IsAuthenticated])
def protected(request):
return Response({'user': request.user.username})How the snippet works
Django REST JWT Auth With Refresh reduces to the functions login and protected.
RefreshToken, api_view, permission_classes, IsAuthenticated, Response are the only symbols borrowed from rest_framework_simplejwt — the coupling is explicit and narrow.
What to watch for
- Plan for an install step:
rest_framework_simplejwtandrest_frameworkare a real dependency, resolved by the package manager.
Applying it
Entry signature: def login(request)
login is the public entry point; everything else in the file exists to support it.
Statements that matter
return Response({
'access': str(refresh.access_token),
'refresh': str(refresh),
})
def protected(request):
return Response({'user': request.user.username})
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `rest_framework_simplejwt` and `rest_framework`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.