11import json
2+
23from jwcrypto import jwk
3- from jose import jwt
4+ from jwcrypto import jwt as jwcrypto_jwt
5+ from jwcrypto .jws import JWS
46
57
68class JWTUtil :
@@ -13,24 +15,59 @@ def generate_jwk(key_type="RSA", size=2048):
1315
1416 @staticmethod
1517 def encode (payload : dict , private_jwk : dict , algorithm = "RS256" ) -> str :
16- return jwt .encode (payload , key = private_jwk , algorithm = algorithm )
18+ # Convert dict to JWK object
19+ key = jwk .JWK (** private_jwk )
20+
21+ # Create JWT object with claims and header
22+ jwt_obj = jwcrypto_jwt .JWT (claims = payload , header = {"alg" : algorithm })
23+
24+ # Sign the token
25+ jwt_obj .make_signed_token (key )
26+
27+ # Serialize to compact format
28+ return jwt_obj .serialize ()
1729
1830 @staticmethod
1931 def decode (token : str , public_jwk : dict , algorithm = "RS256" , options = None ) -> dict :
2032 if options is None :
2133 options = {}
2234
23- options ["verify_aud" ] = options .get ("verify_aud" , False )
35+ # Convert dict to JWK object
36+ key = jwk .JWK (** public_jwk )
37+
38+ # Create JWT object and deserialize
39+ jwt_obj = jwcrypto_jwt .JWT (jwt = token , key = key , algs = [algorithm ])
2440
25- return jwt .decode (token , key = public_jwk , algorithms = algorithm , options = options )
41+ # Validate the token
42+ verify_aud = options .get ("verify_aud" , False )
43+ check_claims = None
44+ if verify_aud and "aud" in options :
45+ check_claims = {"aud" : options ["aud" ]}
46+
47+ if check_claims :
48+ jwt_obj ._check_claims = check_claims
49+
50+ jwt_obj .validate (key )
51+
52+ # Parse claims from JSON string
53+ return json .loads (jwt_obj .claims )
2654
2755 @staticmethod
2856 def unverified_decode (token : str ) -> dict :
29- return jwt .get_unverified_claims (token )
57+ # Deserialize JWS without verification
58+ jws = JWS ()
59+ jws .deserialize (token , None )
60+
61+ # Parse payload from JSON string
62+ payload = jws .payload
63+ if isinstance (payload , bytes ):
64+ payload = payload .decode ("utf-8" )
65+
66+ return json .loads (payload )
3067
3168 @staticmethod
3269 def get_value_from_token (token : str , key : str , default : any = None ) -> any :
3370 try :
3471 return JWTUtil .unverified_decode (token ).get (key , default )
35- except Exception as e :
72+ except Exception :
3673 return default
0 commit comments