@@ -77,8 +77,8 @@ def validate(jwt):
77
77
# Attempt to decode JOSE header
78
78
try :
79
79
jose_header = STRING_TOOLS .urlsafe_b64decode (jwt .split ("." )[0 ])
80
- except UnicodeError :
81
- raise UnicodeError ("Unable to decode JOSE header." )
80
+ except UnicodeError as unicode_error :
81
+ raise UnicodeError ("Unable to decode JOSE header." ) from unicode_error
82
82
# Check for typ and alg in decoded JOSE header
83
83
if "typ" not in jose_header :
84
84
raise TypeError ("JOSE Header does not contain required type key." )
@@ -87,17 +87,19 @@ def validate(jwt):
87
87
# Attempt to decode claim set
88
88
try :
89
89
claims = json .loads (STRING_TOOLS .urlsafe_b64decode (jwt .split ("." )[1 ]))
90
- except UnicodeError :
91
- raise UnicodeError ("Invalid claims encoding." )
90
+ except UnicodeError as unicode_error :
91
+ raise UnicodeError ("Invalid claims encoding." ) from unicode_error
92
92
if not hasattr (claims , "keys" ):
93
93
raise TypeError ("Provided claims is not a JSON dict. object" )
94
94
return (jose_header , claims )
95
95
96
96
@staticmethod
97
- def generate (claims , private_key_data = None , algo = None ):
97
+ def generate (claims , private_key_data = None , algo = None , headers = None ):
98
98
"""Generates and returns a new JSON Web Token.
99
99
:param dict claims: JWT claims set
100
100
:param str private_key_data: Decoded RSA private key data.
101
+ :param str algo: algorithm to be used. One of None, RS256, RS384 or RS512.
102
+ :param dict headers: additional headers for the claim.
101
103
:rtype: str
102
104
"""
103
105
# Allow for unencrypted JWTs
@@ -108,6 +110,8 @@ def generate(claims, private_key_data=None, algo=None):
108
110
# Create the JOSE Header
109
111
# https://tools.ietf.org/html/rfc7519#section-5
110
112
jose_header = {"typ" : "JWT" , "alg" : algo }
113
+ if headers :
114
+ jose_header .update (headers )
111
115
payload = "{}.{}" .format (
112
116
STRING_TOOLS .urlsafe_b64encode (json .dumps (jose_header ).encode ("utf-8" )),
113
117
STRING_TOOLS .urlsafe_b64encode (json .dumps (claims ).encode ("utf-8" )),
@@ -139,8 +143,7 @@ def generate(claims, private_key_data=None, algo=None):
139
143
140
144
# pylint: disable=invalid-name
141
145
class STRING_TOOLS :
142
- """Tools and helpers for URL-safe string encoding.
143
- """
146
+ """Tools and helpers for URL-safe string encoding."""
144
147
145
148
# Some strings for ctype-style character classification
146
149
whitespace = " \t \n \r \v \f "
@@ -179,8 +182,10 @@ def _bytes_from_decode_data(str_data):
179
182
if isinstance (str_data , str ):
180
183
try :
181
184
return str_data .encode ("ascii" )
182
- except :
183
- raise ValueError ("string argument should contain only ASCII characters" )
185
+ except BaseException as error :
186
+ raise ValueError (
187
+ "string argument should contain only ASCII characters"
188
+ ) from error
184
189
elif isinstance (str_data , bit_types ):
185
190
return str_data
186
191
else :
0 commit comments