How to decode token and get back information for djangorestframework-jwt packagefor Django

孤人 提交于 2021-01-24 07:31:16

问题


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......


回答1:


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)



回答2:


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)



回答3:


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')


来源:https://stackoverflow.com/questions/40522177/how-to-decode-token-and-get-back-information-for-djangorestframework-jwt-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!