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})Report a problem with this exampleOpens a pre-filled issue on GitHub.