Django Rest Frame Work를 사용 중이고 세션에서 토큰을 사용하여 인증된 사용자 정보를 얻으려고 합니다.
보기.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
이것은 추적의 나머지 부분입니다
위의 예외를 처리하는 동안 다른 예외가 발생했습니다.
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
토큰은 쿠키에 존재하며 보시는 바와 같이 인쇄되지만 이 오류로 인해 화가 났습니다. 미리 감사합니다.
인코딩 할 때 토큰을 utf-8로 디코딩하십시오.
return jwt.encode(페이로드, settings.SECRET_KEY, algorithm='HS256').decode("utf-8")
그리고 작동하는지 확인
자세한 정보는 여기 https://github.com/jpadilla/pyjwt/issues/319
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다