Skip to content
This repository was archived by the owner on May 26, 2020. It is now read-only.

Commit d8e32b2

Browse files
committed
Merge pull request #7 from stanhu/master
Handle missing fields in JWT payload
2 parents 035266c + 68f0464 commit d8e32b2

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

rest_framework_jwt/authentication.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,14 @@ def authenticate_credentials(self, payload):
6262
Returns an active user that matches the payload's user id and email.
6363
"""
6464
try:
65-
user_id = payload['user_id']
66-
email = payload['email']
67-
user = User.objects.get(pk=user_id, email=email, is_active=True)
65+
user_id = payload.get('user_id')
66+
email = payload.get('email')
67+
68+
if user_id and email:
69+
user = User.objects.get(pk=user_id, email=email, is_active=True)
70+
else:
71+
msg = 'Invalid payload'
72+
raise exceptions.AuthenticationFailed(msg)
6873
except User.DoesNotExist:
6974
msg = 'Invalid signature'
7075
raise exceptions.AuthenticationFailed(msg)

rest_framework_jwt/tests/test_authentication.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,3 +203,19 @@ def test_post_passing_oauth2_with_jwt_auth_priority(self):
203203
HTTP_AUTHORIZATION=auth, format='json')
204204

205205
self.assertEqual(response.status_code, status.HTTP_200_OK, response)
206+
207+
def test_post_form_passing_jwt_invalid_payload(self):
208+
"""
209+
Ensure POSTing json over JWT auth with invalid payload fails
210+
"""
211+
payload = dict(user_id=1, email=None)
212+
token = utils.jwt_encode_handler(payload)
213+
214+
auth = 'JWT {0}'.format(token)
215+
response = self.csrf_client.post(
216+
'/jwt/', {'example': 'example'}, HTTP_AUTHORIZATION=auth)
217+
218+
msg = 'Invalid payload'
219+
220+
self.assertEqual(response.data['detail'], msg)
221+
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)

0 commit comments

Comments
 (0)