diff --git a/jose/jws.py b/jose/jws.py index 63ebb9b9..6f35b75a 100644 --- a/jose/jws.py +++ b/jose/jws.py @@ -17,7 +17,7 @@ from jose.utils import base64url_decode -def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256): +def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256, unencoded=False): """Signs a claims set and returns a JWS string. Args: @@ -29,6 +29,8 @@ def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256): headers will override the default headers. algorithm (str, optional): The algorithm to use for signing the the claims. Defaults to HS256. + unencoded (boolean, optional): If True, the payload is not wrapped + in base64url encoding. Returns: str: The string representation of the header, claims, and signature. @@ -47,7 +49,7 @@ def sign(payload, key, headers=None, algorithm=ALGORITHMS.HS256): raise JWSError('Algorithm %s not supported.' % algorithm) encoded_header = _encode_header(algorithm, additional_headers=headers) - encoded_payload = _encode_payload(payload) + encoded_payload = _encode_payload(payload, unencoded) signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key) return signed_output @@ -135,7 +137,6 @@ def get_unverified_claims(token): def _encode_header(algorithm, additional_headers=None): header = { - "typ": "JWT", "alg": algorithm } @@ -151,7 +152,7 @@ def _encode_header(algorithm, additional_headers=None): return base64url_encode(json_header) -def _encode_payload(payload): +def _encode_payload(payload, unencoded): if isinstance(payload, Mapping): try: payload = json.dumps( @@ -160,8 +161,10 @@ def _encode_payload(payload): ).encode('utf-8') except ValueError: pass - - return base64url_encode(payload) + if unencoded: + return payload + else: + return base64url_encode(payload) def _sign_header_and_claims(encoded_header, encoded_claims, algorithm, key): diff --git a/jose/jwt.py b/jose/jwt.py index ee3b98d4..c88877ad 100644 --- a/jose/jwt.py +++ b/jose/jwt.py @@ -61,6 +61,13 @@ def encode(claims, key, algorithm=ALGORITHMS.HS256, headers=None, access_token=N claims['at_hash'] = calculate_at_hash(access_token, ALGORITHMS.HASHES[algorithm]) + # if a type isn't passed in, set it here + if not headers: + headers = { + 'typ': 'JWT' + } + elif 'typ' not in headers: + headers['typ'] = 'JWT' return jws.sign(claims, key, headers=headers, algorithm=algorithm) diff --git a/tests/test_jws.py b/tests/test_jws.py index dd273398..e6d7d60d 100644 --- a/tests/test_jws.py +++ b/tests/test_jws.py @@ -133,8 +133,7 @@ def test_add_headers(self, payload): expected_headers = { 'test': 'header', - 'alg': 'HS256', - 'typ': 'JWT', + 'alg': 'HS256' } token = jws.sign(payload, 'secret', headers=additional_headers)