如何解码令牌并获取Django的djangorestframework-jwt包的信息

时间:2016-11-10 07:33:38

标签: django python-2.7 django-rest-framework jwt

我已经开始使用djangorestframework-jwt包而不是PyJWT,我只是不知道如何解码传入令牌(我知道有验证令牌方法)....我需要知道的是如何解码令牌并获取信息编码......

3 个答案:

答案 0 :(得分:8)

我使用这种方法来解码令牌并验证用户。首先我没有使用 algorithms=['HS256'] 然后它给出 jwt.exceptions.DecodeError。最后,我添加了它。以下方法对我来说效果很好。

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)

答案 1 :(得分:1)

可能为时已晚,但是我们可以解码jwt并返回有效载荷 使用jwt模块中的jwt.decode

假设您获得的jwt令牌看起来像并且加密的有效载荷位于令牌的中间

{
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MzIxMzg3ODQsImV4cCI6MTUzMjEzOTA4NCwidXNlcl9pZCI6MSwiZW1haWwiOiJwcmF0aWsucHVjc2RAZ21haWwuY29tIiwibXlmIjoxfQ.enG5qiSOPh98YYZBpScHSL5TM8RBz6JhU6uF0l1bZXM"
}

以下是解决方案的摘要:

import jwt
#jwt.decode(<encoded token>,<secret key>,<algorthm>)
decodedPayload = jwt.decode('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MzIxMzg3ODQsImV4cCI6MTUzMjEzOTA4NCwidXNlcl9pZCI6MSwiZW1haWwiOiJwcmF0aWsucHVjc2RAZ21haWwuY29tIiwibXlmIjoxfQ.enG5qiSOPh98YYZBpScHSL5TM8RBz6JhU6uF0l1bZXM',None,None)

答案 2 :(得分:0)

Pratik Charwad提供的答案确实有效,因此我将添加本机的djangorestframework-jwt替代方案,它使用相同的jwt库进行解码:

from rest_framework_jwt.utils import jwt_decode_handler

decoded_payload = jwt_decode_handler('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwib3JpZ19pYXQiOjE1MzIxMzg3ODQsImV4cCI6MTUzMjEzOTA4NCwidXNlcl9pZCI6MSwiZW1haWwiOiJwcmF0aWsucHVjc2RAZ21haWwuY29tIiwibXlmIjoxfQ.enG5qiSOPh98YYZBpScHSL5TM8RBz6JhU6uF0l1bZXM')