Skip to content

Instantly share code, notes, and snippets.

@Angeloem
Created August 6, 2022 11:28
Show Gist options
  • Save Angeloem/f19e296ce9960ca67b718c344ecc0856 to your computer and use it in GitHub Desktop.
Save Angeloem/f19e296ce9960ca67b718c344ecc0856 to your computer and use it in GitHub Desktop.
JWT Authentication
import datetime
import jwt
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import authentication, exceptions
from user.models import User
class JWTAuthentication(authentication.BaseAuthentication):
def authenticate(self, request):
# get the header here
headers = request.META.get('HTTP_AUTHORIZATION')
if not headers:
return None
# decode the jwt
_jwt = str(headers).split(' ').pop()
try:
decoded_jwt = jwt.decode(_jwt, settings.SECRET_KEY, algorithms=["HS256"])
# check if the jwt is valid: not expired
expiry_date = decoded_jwt['exp']
if datetime.datetime.fromtimestamp(int(expiry_date)) < datetime.datetime.now():
raise exceptions.AuthenticationFailed('token expired')
user = User.objects.get(username=decoded_jwt['phone'])
return user, None
except ObjectDoesNotExist:
raise exceptions.AuthenticationFailed('No such user')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment