Skip to content

Instantly share code, notes, and snippets.

@WayneSan
Last active January 7, 2024 20:34
Show Gist options
  • Save WayneSan/7412e1ded25f8192b394 to your computer and use it in GitHub Desktop.
Save WayneSan/7412e1ded25f8192b394 to your computer and use it in GitHub Desktop.
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):
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)
# ...
REST_FRAMEWORK = {
# ...
'DEFAULT_AUTHENTICATION_CLASSES': (
'yourapp.authentication.JSONWebTokenAuthentication',
),
# ...
}
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