Skip to content

Commit ce95501

Browse files
committed
Merge pull request jpadilla#12 from Lothiraldan/master
Add a check in jwt.encode for data type.
2 parents 6d7d9a4 + 35e2a6c commit ce95501

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

jwt/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from time import time
1111
from datetime import datetime
1212
from calendar import timegm
13+
from collections import Mapping
1314

1415
try:
1516
import json
@@ -70,6 +71,11 @@ def header(jwt):
7071
def encode(payload, key, algorithm='HS256'):
7172
segments = []
7273

74+
# Check that we get a mapping
75+
if not isinstance(payload, Mapping):
76+
raise TypeError("Expecting a mapping object, as json web token only"
77+
"support json objects.")
78+
7379
# Header
7480
header = {"typ": "JWT", "alg": algorithm}
7581
segments.append(base64url_encode(json.dumps(header)))

tests/test_jwt.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@ def test_encode_decode(self):
2222
decoded_payload = jwt.decode(jwt_message, secret)
2323
self.assertEqual(decoded_payload, self.payload)
2424

25+
def test_encode_bad_type(self):
26+
27+
types = ['string', tuple(), list(), 42, set()]
28+
29+
for t in types:
30+
with self.assertRaises(TypeError):
31+
jwt.encode(t, 'secret')
32+
2533
def test_encode_expiration_datetime(self):
2634
secret = "secret"
2735
current_datetime = datetime.utcnow()

0 commit comments

Comments
 (0)