I have started using djangorestframework-jwt package instead of PyJWT , I just could not know how to decode the incoming token (I know there is verify token methode).... All I need to know is how to decode the token and get back info encoded......
I use this method to decode tokens and verify the user. First I used without algorithms=['HS256']
then it gives jwt.exceptions.DecodeError. Finally, I added it. Folwing methos worked fine for me.
class VerifyEmail(generics.GenericAPIView):
def get(self, request):
token = request.GET.get('token')
print('payload ' + str(settings.SECRET_KEY))
try:
payload = jwt.decode(jwt=token, key=settings.SECRET_KEY, algorithms=['HS256'])
print('payload 1 ' + str(payload))
user = User.objects.get(id=payload['user_id'])
if not user.is_active:
user.is_active = True
user.save()
return Response({'email': 'Successfully activated'}, status=status.HTTP_200_OK)
except jwt.ExpiredSignatureError as e:
return Response({'error': 'Activations link expired'}, status=status.HTTP_400_BAD_REQUEST)
except jwt.exceptions.DecodeError as e:
return Response({'error': 'Invalid Token'}, status=status.HTTP_400_BAD_REQUEST)
May be its too late to answer, but we can decode jwt and get our payload back using jwt.decode from jwt module
Assume that jwt token you get looks like and your encrypted payload lies in middle of the token
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MzIxMzg3ODQsImV4cCI6MTUzMjEzOTA4NCwidXNlcl9pZCI6MSwiZW1haWwiOiJwcmF0aWsucHVjc2RAZ21haWwuY29tIiwibXlmIjoxfQ.enG5qiSOPh98YYZBpScHSL5TM8RBz6JhU6uF0l1bZXM"
}
Following is snippet for solution:
import jwt
#jwt.decode(<encoded token>,<secret key>,<algorthm>)
decodedPayload = jwt.decode('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MzIxMzg3ODQsImV4cCI6MTUzMjEzOTA4NCwidXNlcl9pZCI6MSwiZW1haWwiOiJwcmF0aWsucHVjc2RAZ21haWwuY29tIiwibXlmIjoxfQ.enG5qiSOPh98YYZBpScHSL5TM8RBz6JhU6uF0l1bZXM',None,None)
The answer provided by Pratik Charwad really works, so I will just add the native djangorestframework-jwt alternative, it uses the same jwt library for decoding:
from rest_framework_jwt.utils import jwt_decode_handler
decoded_payload = jwt_decode_handler('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MzIxMzg3ODQsImV4cCI6MTUzMjEzOTA4NCwidXNlcl9pZCI6MSwiZW1haWwiOiJwcmF0aWsucHVjc2RAZ21haWwuY29tIiwibXlmIjoxfQ.enG5qiSOPh98YYZBpScHSL5TM8RBz6JhU6uF0l1bZXM')
Do this jwt.decode(token,settings.SECRET_KEY, algorithms=['HS256'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With