Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ Major
`#121 <https://github.com/mpdavis/python-jose/pull/121>`_
* Make pyca/cryptography backend the preferred backend if multiple backends are present.
`#122 <https://github.com/mpdavis/python-jose/pull/122>`_
* Allow for headless JWT by sorting headers when serializing.
`#136 <https://github.com/mpdavis/python-jose/pull/136>`_

Bugfixes
""""""""
Expand Down
1 change: 1 addition & 0 deletions jose/jws.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ def _encode_header(algorithm, additional_headers=None):
json_header = json.dumps(
header,
separators=(',', ':'),
sort_keys=True,
).encode('utf-8')

return base64url_encode(json_header)
Expand Down
27 changes: 27 additions & 0 deletions tests/test_jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,33 @@ def test_non_default_headers(self, claims, key, headers):
for k, v in headers.items():
assert all_headers[k] == v

def test_deterministic_headers(self):
from collections import OrderedDict
from jose.utils import base64url_decode

claims = {"a": "b"}
key = "secret"

headers1 = OrderedDict((
('kid', 'my-key-id'),
('another_key', 'another_value'),
))
encoded1 = jwt.encode(claims, key, algorithm='HS256', headers=headers1)
encoded_headers1 = encoded1.split('.', 1)[0]

headers2 = OrderedDict((
('another_key', 'another_value'),
('kid', 'my-key-id'),
))
encoded2 = jwt.encode(claims, key, algorithm='HS256', headers=headers2)
encoded_headers2 = encoded2.split('.', 1)[0]

assert encoded_headers1 == encoded_headers2

# manually decode header to compare it to known good
decoded_headers1 = base64url_decode(encoded_headers1.encode('utf-8'))
assert decoded_headers1 == b"""{"alg":"HS256","another_key":"another_value","kid":"my-key-id","typ":"JWT"}"""

def test_encode(self, claims, key):

expected = (
Expand Down