77
88try :
99 import jwt
10+ import jwt .utils
1011except ImportError :
1112 jwt = None
1213
14+ try :
15+ from cryptography .hazmat .primitives .serialization import load_pem_private_key
16+ except ImportError :
17+ load_pem_private_key = None
18+
1319
1420class Token (abc .ABC ):
1521 def __init__ (self , token : str , token_type : str ):
@@ -36,18 +42,19 @@ def token(self) -> Token:
3642
3743class JwtTokenSource (TokenSource ):
3844 def __init__ (
39- self ,
40- signing_method : str ,
41- private_key : typing .Optional [str ] = None ,
42- private_key_file : typing .Optional [str ] = None ,
43- key_id : typing .Optional [str ] = None ,
44- issuer : typing .Optional [str ] = None ,
45- subject : typing .Optional [str ] = None ,
46- audience : typing .Union [typing .List [str ], str , None ] = None ,
47- id : typing .Optional [str ] = None ,
48- token_ttl_seconds : int = 3600 ,
45+ self ,
46+ signing_method : str ,
47+ private_key : typing .Optional [str ] = None ,
48+ private_key_file : typing .Optional [str ] = None ,
49+ key_id : typing .Optional [str ] = None ,
50+ issuer : typing .Optional [str ] = None ,
51+ subject : typing .Optional [str ] = None ,
52+ audience : typing .Union [typing .List [str ], str , None ] = None ,
53+ id : typing .Optional [str ] = None ,
54+ token_ttl_seconds : int = 3600 ,
4955 ):
5056 assert jwt is not None , "Install pyjwt library to use jwt tokens"
57+ assert load_pem_private_key is not None , "Install cryptography library to use jwt tokens"
5158 self ._signing_method = signing_method
5259 self ._key_id = key_id
5360 if private_key and private_key_file :
@@ -57,7 +64,7 @@ def __init__(
5764 self ._private_key = private_key
5865 if private_key_file :
5966 private_key_file = os .path .expanduser (private_key_file )
60- with open (private_key_file , "r " ) as key_file :
67+ with open (private_key_file , "rb " ) as key_file :
6168 self ._private_key = key_file .read ()
6269 self ._issuer = issuer
6370 self ._subject = subject
@@ -70,6 +77,10 @@ def __init__(
7077 raise Exception ("JWT: no private key specified" )
7178 if self ._token_ttl_seconds <= 0 :
7279 raise Exception ("JWT: invalid jwt token TTL" )
80+ if isinstance (self ._private_key , str ):
81+ self ._private_key = self ._private_key .encode ()
82+ if isinstance (self ._private_key , bytes ) and jwt .utils .is_pem_format (self ._private_key ):
83+ self ._private_key = load_pem_private_key (self ._private_key , password = None )
7384
7485 def token (self ) -> Token :
7586 now = time .time ()
0 commit comments