Django REST JWT Auth With Refresh

Implement JWT authentication with access and refresh tokens in Django REST Framework.

PythonAuth Jwt

Code

pythonsnippet
20 lines
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_simplejwt and rest_framework are 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

FAQ

Which packages must be installed first?
Yes. The imports resolve to `rest_framework_simplejwt` and `rest_framework`, which the package manager must provide.