-
-
Save catogonzalez/2956b6659aeb13e6061f1e4ccb784072 to your computer and use it in GitHub Desktop.
PyJWT + Django REST framework 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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): | |
try: | |
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ... | |
REST_FRAMEWORK = { | |
# ... | |
'DEFAULT_AUTHENTICATION_CLASSES': ( | |
'yourapp.authentication.JSONWebTokenAuthentication', | |
), | |
# ... | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from .views import json_web_token_auth | |
urlpatterns = [ | |
url(r'^token/', json_web_token_auth), | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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