Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
PyJWT + Django REST framework 2
import jwt
from django.conf import settings
from django.contrib.auth.models import User
from rest_framework import exceptions
from rest_framework.authentication import TokenAuthentication
class JSONWebTokenAuthentication(TokenAuthentication):
def authenticate_credentials(self, key):
payload = jwt.decode(key, settings.SECRET_KEY)
user = User.objects.get(username=payload['username'])
except (jwt.DecodeError, User.DoesNotExist):
raise exceptions.AuthenticationFailed('Invalid token')
except jwt.ExpiredSignatureError:
raise exceptions.AuthenticationFailed('Token has expired')
if not user.is_active:
raise exceptions.AuthenticationFailed('User inactive or deleted')
return (user, payload)
# ...
# ...
# ...
from .views import json_web_token_auth
urlpatterns = [
url(r'^token/', json_web_token_auth),
import datetime
import jwt
from django.conf import settings
from rest_framework import parsers, renderers, status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authtoken.serializers import AuthTokenSerializer
class JSONWebTokenAuth(APIView):
throttle_classes = ()
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
def post(self, request):
serializer = self.serializer_class(data=request.DATA)
if serializer.is_valid():
user = serializer.object['user']
token = jwt.encode({
'username': user.username,
'iat': datetime.datetime.utcnow(),
'nbf': datetime.datetime.utcnow() + datetime.timedelta(minutes=-5),
'exp': datetime.datetime.utcnow() + datetime.timedelta(days=7)
}, settings.SECRET_KEY)
return Response({'token': token})
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
json_web_token_auth = JSONWebTokenAuth.as_view()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment