簡體   English   中英

Django Rest 框架 PyJWT 令牌無效 header 填充

[英]Django Rest Framework PyJWT Token Invalid header padding

我正在使用 Django Rest 框架,我正在嘗試使用 session 中的令牌獲取經過身份驗證的用戶信息

視圖.py:

# Get Authenticated User Data
class UserAPIView(APIView):
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response(UserSerializer(request.user).data)

JWT身份驗證

class JWTAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.COOKIES.get('jwt')
        print('token = ', token)

        if not token:
            return None

        try:
            payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
            print('payload = ', payload)
        except jwt.ExpiredSignatureError:
            raise exceptions.AuthenticationFailed('unauthenticated')

        user = User.objects.get(pk=payload['user_id'])

        if not user:
            raise exceptions.AuthenticationFailed('User not found!')

        return (user, None)

    @staticmethod
    def generate_jwt(id):
        payload = {
            'user_id': id,
            'exp': datetime.datetime.now() + datetime.timedelta(days=1),
            'iat': datetime.datetime.utcnow()
        }
        return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')

但我得到了這個錯誤

Invalid header padding 

這是回溯

[08/Jun/2021 10:44:09] "GET /api/account/user/ HTTP/1.1" 500 134862
token =  b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE2MjMyMzU0NDcsImlhdCI6MTYyMzE0MTg0N30.qnNZw3M5YiLMalc78wknjtuTOztHbjyr2swHyK1xuGY'
Internal Server Error: /api/account/user/
Traceback (most recent call last):
  File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\api_jws.py", line 186, in _load
    header_data = base64url_decode(header_segment)
  File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\utils.py", line 42, in base64url_decode
    return base64.urlsafe_b64decode(input)
  File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\base64.py", line 133, in urlsafe_b64decode
    return b64decode(s)
  File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Invalid base64-encoded string: number of data characters (37) cannot be 1 more than a multiple of 4

這是 Traceback 的 rest

在處理上述異常的過程中,又出現了一個異常:

  File "D:\Private\PythonProjects\ProCoders-02\src\Pepsi\profession\backend\blog\api\API_Authentication.py", line 20, in authenticate
    payload = jwt.decode(token, settings.SECRET_KEY, algorithms=['HS256'])
  File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\api_jwt.py", line 84, in decode
    payload, _, _, _ = self._load(jwt)
  File "C:\Users\MAbbas\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\api_jws.py", line 188, in _load
    raise DecodeError('Invalid header padding')
jwt.exceptions.DecodeError: Invalid header padding

修改 No.01(添加 LogInView 以顯示我如何保存令牌)

登錄查看

class LoginAPIView(APIView):
    def post(self, request):
        email = request.data['email']
        password = request.data['password']

        user = User.objects.filter(email=email).first()

        if user is None:
            raise exceptions.AuthenticationFailed('User not found!')

        if not user.check_password(password):
            raise exceptions.AuthenticationFailed('Incorrect Password!')

        token = JWTAuthentication.generate_jwt(user.id)

        response = Response()
        response.set_cookie(key='jwt', value=token, httponly=True)
        response.data = {
            'message': 'success'
        }

        return response

令牌存在於 cookies 中並如您所見打印,但這個錯誤讓我很生氣 提前致謝

嘗試在編碼時將令牌解碼為 utf-8

return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256').decode("utf-8")

並檢查它是否有效

更多信息在這里https://github.com/jpadilla/pyjwt/issues/319

我認為問題可能出在您編碼 jwt 的方式上,在您的有效負載中嘗試將“exp”值轉換為 int 值,如下所示:payload = { 'user_id': id, 'exp': int(datetime.datetime .now() + datetime.timedelta(days=1)), 'iat': int(datetime.datetime.utcnow()) } return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256')

我相信 exp 和 iat 值必須是數字

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM