usso-jwt 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jwt/__init__.py ADDED
File without changes
@@ -0,0 +1,37 @@
1
+ from typing import Type
2
+
3
+ from .base import Algorithm
4
+ from .ecdsa import ECDSAAlgorithm
5
+ from .eddsa import EdDSAAlgorithm
6
+ from .hmac import HMACAlgorithm
7
+ from .rsa import RSAAlgorithm
8
+
9
+
10
+ def get_algorithm(alg: str) -> Type[Algorithm]:
11
+ """
12
+ Get the appropriate algorithm manager for the given algorithm.
13
+
14
+ Args:
15
+ alg: The algorithm name (e.g., "HS256", "RS256", "ES256", "EdDSA")
16
+
17
+ Returns:
18
+ The appropriate algorithm manager class
19
+
20
+ Raises:
21
+ ValueError: If the algorithm is not supported
22
+ """
23
+ for algo in Algorithm.__subclasses__():
24
+ if alg.upper() in algo.SUPPORTED_ALGORITHMS:
25
+ return algo
26
+
27
+ raise ValueError(f"Unsupported algorithm: {alg}")
28
+
29
+
30
+ __all__ = [
31
+ "Algorithm",
32
+ "HMACAlgorithm",
33
+ "RSAAlgorithm",
34
+ "ECDSAAlgorithm",
35
+ "EdDSAAlgorithm",
36
+ "get_algorithm",
37
+ ]
jwt/algorithms/base.py ADDED
@@ -0,0 +1,38 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+
4
+ class Algorithm(ABC):
5
+ """Abstract base class for JWT algorithms."""
6
+
7
+ @property
8
+ @abstractmethod
9
+ def SUPPORTED_ALGORITHMS(self) -> set[str]:
10
+ """Set of supported algorithms for this implementation."""
11
+
12
+ @staticmethod
13
+ @abstractmethod
14
+ def load_key(key: dict | bytes, password: bytes | None = None):
15
+ """Load key from JWK dict or raw bytes."""
16
+
17
+ @classmethod
18
+ @abstractmethod
19
+ def sign(
20
+ cls,
21
+ signing_input: bytes,
22
+ key: dict | bytes,
23
+ alg: str,
24
+ password: bytes | None = None,
25
+ ) -> bytes:
26
+ """Sign data using the specified algorithm."""
27
+
28
+ @classmethod
29
+ @abstractmethod
30
+ def verify(
31
+ cls,
32
+ signing_input: bytes,
33
+ signature: bytes,
34
+ key: dict | bytes,
35
+ alg: str,
36
+ password: bytes | None = None,
37
+ ) -> bool:
38
+ """Verify signature using the specified algorithm."""
@@ -0,0 +1,131 @@
1
+ import base64
2
+
3
+ from cryptography.hazmat.backends import default_backend
4
+ from cryptography.hazmat.primitives import hashes, serialization
5
+ from cryptography.hazmat.primitives.asymmetric import ec, utils
6
+
7
+ from .base import Algorithm
8
+
9
+
10
+ class ECDSAAlgorithm(Algorithm):
11
+ """ECDSA algorithm implementation (ES256, ES384, ES512)."""
12
+
13
+ SUPPORTED_ALGORITHMS = {
14
+ "ES256": ec.SECP256R1,
15
+ "ES384": ec.SECP384R1,
16
+ "ES512": ec.SECP521R1,
17
+ }
18
+
19
+ @classmethod
20
+ def load_key(
21
+ cls, key: dict | bytes, alg: str, password: bytes | None = None
22
+ ) -> ec.EllipticCurvePrivateKey:
23
+ """
24
+ Load ECDSA private key from JWK dict or PEM bytes.
25
+
26
+ Args:
27
+ key: Either a JWK dict or PEM-encoded private key bytes
28
+ alg: The signing algorithm (ES256, ES384, ES512)
29
+ password: Optional password for encrypted PEM keys
30
+
31
+ Returns:
32
+ ECDSA private key object
33
+ """
34
+ if alg not in cls.SUPPORTED_ALGORITHMS:
35
+ raise ValueError(f"Unsupported ECDSA algorithm: {alg}")
36
+
37
+ if isinstance(key, dict):
38
+ # Load from JWK
39
+ curve = cls.SUPPORTED_ALGORITHMS[alg]()
40
+ x = int.from_bytes(base64.urlsafe_b64decode(key["x"]), "big")
41
+ y = int.from_bytes(base64.urlsafe_b64decode(key["y"]), "big")
42
+ d = int.from_bytes(base64.urlsafe_b64decode(key["d"]), "big")
43
+
44
+ return ec.EllipticCurvePrivateNumbers(
45
+ d, ec.EllipticCurvePublicNumbers(x, y, curve)
46
+ ).private_key(default_backend())
47
+ else:
48
+ # Load from PEM
49
+ return serialization.load_pem_private_key(
50
+ key, password=password, backend=default_backend()
51
+ )
52
+
53
+ @classmethod
54
+ def sign(
55
+ cls,
56
+ signing_input: bytes,
57
+ key: dict | bytes,
58
+ alg: str,
59
+ password: bytes | None = None,
60
+ ) -> bytes:
61
+ """
62
+ Sign using ECDSA algorithms.
63
+
64
+ Args:
65
+ signing_input: The data to sign
66
+ key: Either a JWK dict or PEM-encoded private key bytes
67
+ alg: The signing algorithm to use (ES256, ES384, ES512)
68
+ password: Optional password for encrypted PEM keys
69
+
70
+ Returns:
71
+ The signature
72
+ """
73
+ if alg not in cls.SUPPORTED_ALGORITHMS:
74
+ raise ValueError(f"Unsupported ECDSA algorithm: {alg}")
75
+
76
+ privkey = cls.load_key(key, alg, password)
77
+
78
+ # Sign and format signature
79
+ signature = privkey.sign(signing_input, ec.ECDSA(hashes.SHA256()))
80
+ r, s = utils.decode_dss_signature(signature)
81
+ size = (privkey.curve.key_size + 7) // 8
82
+ return r.to_bytes(size, "big") + s.to_bytes(size, "big")
83
+
84
+ @classmethod
85
+ def verify(
86
+ cls,
87
+ signing_input: bytes,
88
+ signature: bytes,
89
+ key: dict | bytes,
90
+ alg: str,
91
+ password: bytes | None = None,
92
+ ) -> bool:
93
+ """
94
+ Verify ECDSA signature.
95
+
96
+ Args:
97
+ signing_input: The data that was signed
98
+ signature: The signature to verify
99
+ key: Either a JWK dict or PEM-encoded public key bytes
100
+ alg: The signing algorithm used (ES256, ES384, ES512)
101
+ password: Optional password for encrypted PEM keys
102
+
103
+ Returns:
104
+ True if signature is valid, False otherwise
105
+ """
106
+ if alg not in cls.SUPPORTED_ALGORITHMS:
107
+ raise ValueError(f"Unsupported ECDSA algorithm: {alg}")
108
+
109
+ if isinstance(key, dict):
110
+ # Load from JWK
111
+ curve = cls.SUPPORTED_ALGORITHMS[alg]()
112
+ x = int.from_bytes(base64.urlsafe_b64decode(key["x"]), "big")
113
+ y = int.from_bytes(base64.urlsafe_b64decode(key["y"]), "big")
114
+ pubkey = ec.EllipticCurvePublicNumbers(x, y, curve).public_key(
115
+ default_backend()
116
+ )
117
+ else:
118
+ # Load from PEM
119
+ pubkey = serialization.load_pem_public_key(key, backend=default_backend())
120
+
121
+ try:
122
+ # Reconstruct signature from r and s components
123
+ size = (pubkey.curve.key_size + 7) // 8
124
+ r = int.from_bytes(signature[:size], "big")
125
+ s = int.from_bytes(signature[size:], "big")
126
+ sig = utils.encode_dss_signature(r, s)
127
+
128
+ pubkey.verify(sig, signing_input, ec.ECDSA(hashes.SHA256()))
129
+ return True
130
+ except Exception:
131
+ return False
@@ -0,0 +1,95 @@
1
+ import base64
2
+
3
+ from cryptography.hazmat.primitives.asymmetric import ed25519
4
+
5
+ from .base import Algorithm
6
+
7
+
8
+ class EdDSAAlgorithm(Algorithm):
9
+ """EdDSA algorithm implementation (Ed25519)."""
10
+
11
+ SUPPORTED_ALGORITHMS = {"EdDSA"}
12
+
13
+ @staticmethod
14
+ def load_key(
15
+ key: dict | bytes, password: bytes | None = None
16
+ ) -> ed25519.Ed25519PrivateKey:
17
+ """
18
+ Load EdDSA private key from JWK dict or raw bytes.
19
+
20
+ Args:
21
+ key: Either a JWK dict or raw private key bytes
22
+ password: Optional password for encrypted keys
23
+
24
+ Returns:
25
+ EdDSA private key object
26
+ """
27
+ if isinstance(key, dict):
28
+ return ed25519.Ed25519PrivateKey.from_private_bytes(
29
+ base64.urlsafe_b64decode(key["d"])
30
+ )
31
+ return ed25519.Ed25519PrivateKey.from_private_bytes(key)
32
+
33
+ @classmethod
34
+ def sign(
35
+ cls,
36
+ signing_input: bytes,
37
+ key: dict | bytes,
38
+ alg: str,
39
+ password: bytes | None = None,
40
+ ) -> bytes:
41
+ """
42
+ Sign using EdDSA algorithm.
43
+
44
+ Args:
45
+ signing_input: The data to sign
46
+ key: Either a JWK dict or raw private key bytes
47
+ alg: The signing algorithm to use (must be "EdDSA")
48
+ password: Optional password for encrypted keys
49
+
50
+ Returns:
51
+ The signature
52
+ """
53
+ if alg not in cls.SUPPORTED_ALGORITHMS:
54
+ raise ValueError(f"Unsupported EdDSA algorithm: {alg}")
55
+
56
+ privkey = cls.load_key(key, password)
57
+ return privkey.sign(signing_input)
58
+
59
+ @classmethod
60
+ def verify(
61
+ cls,
62
+ signing_input: bytes,
63
+ signature: bytes,
64
+ key: dict | bytes,
65
+ alg: str,
66
+ password: bytes | None = None,
67
+ ) -> bool:
68
+ """
69
+ Verify EdDSA signature.
70
+
71
+ Args:
72
+ signing_input: The data that was signed
73
+ signature: The signature to verify
74
+ key: Either a JWK dict or raw public key bytes
75
+ alg: The signing algorithm used (must be "EdDSA")
76
+ password: Optional password for encrypted keys
77
+
78
+ Returns:
79
+ True if signature is valid, False otherwise
80
+ """
81
+ if alg not in cls.SUPPORTED_ALGORITHMS:
82
+ raise ValueError(f"Unsupported EdDSA algorithm: {alg}")
83
+
84
+ if isinstance(key, dict):
85
+ pubkey = ed25519.Ed25519PublicKey.from_public_bytes(
86
+ base64.urlsafe_b64decode(key["x"])
87
+ )
88
+ else:
89
+ pubkey = ed25519.Ed25519PublicKey.from_public_bytes(key)
90
+
91
+ try:
92
+ pubkey.verify(signature, signing_input)
93
+ return True
94
+ except Exception:
95
+ return False
jwt/algorithms/hmac.py ADDED
@@ -0,0 +1,98 @@
1
+ import base64
2
+
3
+ from cryptography.hazmat.backends import default_backend
4
+ from cryptography.hazmat.primitives import hashes, hmac
5
+
6
+ from .base import Algorithm
7
+
8
+
9
+ class HMACAlgorithm(Algorithm):
10
+ """HMAC algorithm implementation (HS256, HS384, HS512)."""
11
+
12
+ SUPPORTED_ALGORITHMS = {
13
+ "HS256": hashes.SHA256,
14
+ "HS384": hashes.SHA384,
15
+ "HS512": hashes.SHA512,
16
+ }
17
+
18
+ @staticmethod
19
+ def load_key(key: dict | bytes, password: bytes | None = None) -> bytes:
20
+ """
21
+ Load HMAC key from JWK dict or raw bytes.
22
+
23
+ Args:
24
+ key: Either a JWK dict or raw key bytes
25
+ password: Optional password for encrypted keys
26
+
27
+ Returns:
28
+ HMAC key bytes
29
+ """
30
+ if isinstance(key, dict):
31
+ return base64.urlsafe_b64decode(key["k"])
32
+ return key
33
+
34
+ @classmethod
35
+ def sign(
36
+ cls,
37
+ signing_input: bytes,
38
+ key: dict | bytes,
39
+ alg: str,
40
+ password: bytes | None = None,
41
+ ) -> bytes:
42
+ """
43
+ Sign using HMAC algorithms.
44
+
45
+ Args:
46
+ signing_input: The data to sign
47
+ key: Either a JWK dict or raw key bytes
48
+ alg: The signing algorithm to use (HS256, HS384, HS512)
49
+ password: Optional password for encrypted keys
50
+
51
+ Returns:
52
+ The signature
53
+ """
54
+ if alg not in cls.SUPPORTED_ALGORITHMS:
55
+ raise ValueError(f"Unsupported HMAC algorithm: {alg}")
56
+
57
+ key_bytes = cls.load_key(key, password)
58
+ h = hmac.HMAC(
59
+ key_bytes, cls.SUPPORTED_ALGORITHMS[alg](), backend=default_backend()
60
+ )
61
+ h.update(signing_input)
62
+ return h.finalize()
63
+
64
+ @classmethod
65
+ def verify(
66
+ cls,
67
+ signing_input: bytes,
68
+ signature: bytes,
69
+ key: dict | bytes,
70
+ alg: str,
71
+ password: bytes | None = None,
72
+ ) -> bool:
73
+ """
74
+ Verify HMAC signature.
75
+
76
+ Args:
77
+ signing_input: The data that was signed
78
+ signature: The signature to verify
79
+ key: Either a JWK dict or raw key bytes
80
+ alg: The signing algorithm used (HS256, HS384, HS512)
81
+ password: Optional password for encrypted keys
82
+
83
+ Returns:
84
+ True if signature is valid, False otherwise
85
+ """
86
+ if alg not in cls.SUPPORTED_ALGORITHMS:
87
+ raise ValueError(f"Unsupported HMAC algorithm: {alg}")
88
+
89
+ key_bytes = cls.load_key(key, password)
90
+ h = hmac.HMAC(
91
+ key_bytes, cls.SUPPORTED_ALGORITHMS[alg](), backend=default_backend()
92
+ )
93
+ h.update(signing_input)
94
+ try:
95
+ h.verify(signature)
96
+ return True
97
+ except Exception:
98
+ return False
jwt/algorithms/rsa.py ADDED
@@ -0,0 +1,143 @@
1
+ import base64
2
+
3
+ from cryptography.hazmat.backends import default_backend
4
+ from cryptography.hazmat.primitives import hashes, serialization
5
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
6
+
7
+ from .base import Algorithm
8
+
9
+
10
+ class RSAAlgorithm(Algorithm):
11
+ """RSA algorithm implementation (RS256, RS384, RS512, PS256, PS384, PS512)."""
12
+
13
+ SUPPORTED_ALGORITHMS = {
14
+ "RS256": hashes.SHA256,
15
+ "RS384": hashes.SHA384,
16
+ "RS512": hashes.SHA512,
17
+ "PS256": hashes.SHA256,
18
+ "PS384": hashes.SHA384,
19
+ "PS512": hashes.SHA512,
20
+ }
21
+
22
+ @staticmethod
23
+ def load_key(key: dict | bytes, password: bytes | None = None) -> rsa.RSAPrivateKey:
24
+ """
25
+ Load RSA private key from JWK dict or PEM bytes.
26
+
27
+ Args:
28
+ key: Either a JWK dict or PEM-encoded private key bytes
29
+ password: Optional password for encrypted PEM keys
30
+
31
+ Returns:
32
+ RSA private key object
33
+ """
34
+ if isinstance(key, dict):
35
+ # Load from JWK
36
+ n = int.from_bytes(base64.urlsafe_b64decode(key["n"]), "big")
37
+ e = int.from_bytes(base64.urlsafe_b64decode(key["e"]), "big")
38
+ d = int.from_bytes(base64.urlsafe_b64decode(key["d"]), "big")
39
+ return rsa.RSAPrivateNumbers(
40
+ p=int.from_bytes(base64.urlsafe_b64decode(key["p"]), "big"),
41
+ q=int.from_bytes(base64.urlsafe_b64decode(key["q"]), "big"),
42
+ d=d,
43
+ dmp1=int.from_bytes(base64.urlsafe_b64decode(key["dp"]), "big"),
44
+ dmq1=int.from_bytes(base64.urlsafe_b64decode(key["dq"]), "big"),
45
+ iqmp=int.from_bytes(base64.urlsafe_b64decode(key["qi"]), "big"),
46
+ public_numbers=rsa.RSAPublicNumbers(e, n),
47
+ ).private_key(default_backend())
48
+ else:
49
+ # Load from PEM
50
+ return serialization.load_pem_private_key(
51
+ key, password=password, backend=default_backend()
52
+ )
53
+
54
+ @classmethod
55
+ def sign(
56
+ cls,
57
+ signing_input: bytes,
58
+ key: dict | bytes,
59
+ alg: str,
60
+ password: bytes | None = None,
61
+ ) -> bytes:
62
+ """
63
+ Sign using RSA algorithms.
64
+
65
+ Args:
66
+ signing_input: The data to sign
67
+ key: Either a JWK dict or PEM-encoded private key bytes
68
+ alg: The signing algorithm to use (RS256, RS384, RS512, PS256, PS384, PS512)
69
+ password: Optional password for encrypted PEM keys
70
+
71
+ Returns:
72
+ The signature
73
+ """
74
+ if alg not in cls.SUPPORTED_ALGORITHMS:
75
+ raise ValueError(f"Unsupported RSA algorithm: {alg}")
76
+
77
+ privkey = cls.load_key(key, password)
78
+ hash_alg = cls.SUPPORTED_ALGORITHMS[alg]
79
+
80
+ if alg.startswith("RS"):
81
+ return privkey.sign(signing_input, padding.PKCS1v15(), hash_alg())
82
+ else: # PS
83
+ return privkey.sign(
84
+ signing_input,
85
+ padding.PSS(
86
+ mgf=padding.MGF1(hash_alg()),
87
+ salt_length=hashes.SHA256().digest_size,
88
+ ),
89
+ hash_alg(),
90
+ )
91
+
92
+ @classmethod
93
+ def verify(
94
+ cls,
95
+ signing_input: bytes,
96
+ signature: bytes,
97
+ key: dict | bytes,
98
+ alg: str,
99
+ password: bytes | None = None,
100
+ ) -> bool:
101
+ """
102
+ Verify RSA signature.
103
+
104
+ Args:
105
+ signing_input: The data that was signed
106
+ signature: The signature to verify
107
+ key: Either a JWK dict or PEM-encoded public key bytes
108
+ alg: The signing algorithm used (RS256, RS384, RS512, PS256, PS384, PS512)
109
+ password: Optional password for encrypted PEM keys
110
+
111
+ Returns:
112
+ True if signature is valid, False otherwise
113
+ """
114
+ if alg not in cls.SUPPORTED_ALGORITHMS:
115
+ raise ValueError(f"Unsupported RSA algorithm: {alg}")
116
+
117
+ if isinstance(key, dict):
118
+ # Load from JWK
119
+ n = int.from_bytes(base64.urlsafe_b64decode(key["n"]), "big")
120
+ e = int.from_bytes(base64.urlsafe_b64decode(key["e"]), "big")
121
+ pubkey = rsa.RSAPublicNumbers(e, n).public_key(default_backend())
122
+ else:
123
+ # Load from PEM
124
+ pubkey = serialization.load_pem_public_key(key, backend=default_backend())
125
+
126
+ hash_alg = cls.SUPPORTED_ALGORITHMS[alg]
127
+
128
+ try:
129
+ if alg.startswith("RS"):
130
+ pubkey.verify(signature, signing_input, padding.PKCS1v15(), hash_alg())
131
+ else: # PS
132
+ pubkey.verify(
133
+ signature,
134
+ signing_input,
135
+ padding.PSS(
136
+ mgf=padding.MGF1(hash_alg()),
137
+ salt_length=hashes.SHA256().digest_size,
138
+ ),
139
+ hash_alg(),
140
+ )
141
+ return True
142
+ except Exception:
143
+ return False
jwt/core.py ADDED
@@ -0,0 +1,26 @@
1
+ from enum import Enum
2
+
3
+
4
+ class Algorithm(str, Enum):
5
+ # HMAC with SHA-2
6
+ HS256 = "HS256" # HMAC with SHA-256
7
+ HS384 = "HS384" # HMAC with SHA-384
8
+ HS512 = "HS512" # HMAC with SHA-512
9
+
10
+ # RSA with SHA-2
11
+ RS256 = "RS256" # RSA with SHA-256
12
+ RS384 = "RS384" # RSA with SHA-384
13
+ RS512 = "RS512" # RSA with SHA-512
14
+
15
+ # ECDSA with SHA-2
16
+ ES256 = "ES256" # ECDSA with SHA-256
17
+ ES384 = "ES384" # ECDSA with SHA-384
18
+ ES512 = "ES512" # ECDSA with SHA-512
19
+
20
+ # RSASSA-PSS with SHA-2
21
+ PS256 = "PS256" # RSASSA-PSS with SHA-256
22
+ PS384 = "PS384" # RSASSA-PSS with SHA-384
23
+ PS512 = "PS512" # RSASSA-PSS with SHA-512
24
+
25
+ # EdDSA with SHA-2
26
+ EdDSA = "EDDSA" # EdDSA with SHA-512
jwt/exceptions.py ADDED
@@ -0,0 +1,29 @@
1
+ """JWT-related exceptions."""
2
+
3
+
4
+ class JWTError(Exception):
5
+ """Base exception for JWT-related errors."""
6
+
7
+
8
+ class JWTExpiredError(JWTError):
9
+ """Raised when a JWT has expired."""
10
+
11
+
12
+ class JWTNotValidYetError(JWTError):
13
+ """Raised when a JWT's 'nbf' claim indicates it's not valid yet."""
14
+
15
+
16
+ class JWTIssuedInFutureError(JWTError):
17
+ """Raised when a JWT's 'iat' claim is in the future."""
18
+
19
+
20
+ class JWTInvalidSignatureError(JWTError):
21
+ """Raised when a JWT's signature is invalid."""
22
+
23
+
24
+ class JWTInvalidFormatError(JWTError):
25
+ """Raised when a JWT has an invalid format."""
26
+
27
+
28
+ class JWKNotFoundError(JWTError):
29
+ """Raised when a JWK with the specified kid is not found."""
jwt/jwt.py ADDED
@@ -0,0 +1,86 @@
1
+ from typing import TypeVar
2
+
3
+ from cachetools import TTLCache, cached
4
+ from pydantic import BaseModel
5
+
6
+ from .core import Algorithm
7
+ from .verify import (
8
+ extract_jwt_parts,
9
+ fetch_jwk,
10
+ verify_signature,
11
+ verify_temporal_claims,
12
+ )
13
+
14
+ T = TypeVar("T", bound="BaseModel")
15
+
16
+
17
+ class JWT(BaseModel):
18
+ token: str
19
+ key: dict | None = None
20
+ jwks_url: str | None = None
21
+
22
+ def __init__(
23
+ self,
24
+ *,
25
+ token: str,
26
+ key: dict | None = None,
27
+ payload_class: type[T] | None = None,
28
+ ):
29
+ super().__init__(token=token, key=key)
30
+ self.payload_class = payload_class
31
+
32
+ @property
33
+ @cached(cache=TTLCache(maxsize=1000, ttl=300))
34
+ def _parts(self) -> tuple[dict, dict, bytes, bytes]:
35
+ return extract_jwt_parts(self.token)
36
+
37
+ @property
38
+ def unverified_header(self) -> dict[str, str]:
39
+ return self._parts[0]
40
+
41
+ @property
42
+ def algorithm(self) -> Algorithm:
43
+ return Algorithm(self.unverified_header["alg"].upper())
44
+
45
+ @property
46
+ def unverified_payload(self) -> dict | T:
47
+ if self.payload_class is not None:
48
+ return self.payload_class.model_validate(self._parts[1])
49
+ return self._parts[1]
50
+
51
+ @property
52
+ def _signature(self) -> bytes:
53
+ return self._parts[2]
54
+
55
+ @property
56
+ def _signing_input(self) -> bytes:
57
+ return self._parts[3]
58
+
59
+ def verify(self) -> bool:
60
+ if self.jwks_url is None and self.key is None:
61
+ raise ValueError("Either jwks_url or key must be provided")
62
+
63
+ if self.jwks_url is not None:
64
+ self.key = fetch_jwk(self.unverified_header["kid"], self.jwks_url)
65
+
66
+ if self.key is None:
67
+ raise ValueError("Key must be provided")
68
+
69
+ verification = verify_signature(
70
+ self.algorithm, self.key, self._signing_input, self._signature
71
+ )
72
+ if not verification:
73
+ return False
74
+ return verify_temporal_claims(self.unverified_payload)
75
+
76
+ @property
77
+ def verified_payload(self) -> dict | T:
78
+ if self.verify():
79
+ return self.unverified_payload
80
+ raise ValueError("JWT is not valid")
81
+
82
+ @property
83
+ def verified_header(self) -> dict:
84
+ if self.verify():
85
+ return self.unverified_header
86
+ raise ValueError("JWT is not valid")
jwt/sign.py ADDED
@@ -0,0 +1,82 @@
1
+ import base64
2
+ import time
3
+
4
+ import json_advanced as json
5
+
6
+ from .algorithms import get_algorithm
7
+
8
+
9
+ def b64url_encode(data: bytes) -> str:
10
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
11
+
12
+
13
+ def create_jwt_header(alg: str, kid: str | None = None, **kwargs) -> dict:
14
+ header = {"alg": alg, "typ": "JWT"}
15
+ if kid:
16
+ header["kid"] = kid
17
+ header.update(kwargs)
18
+ return header
19
+
20
+
21
+ def sign_jwt_parts(
22
+ header: dict,
23
+ payload: dict,
24
+ key: dict | bytes,
25
+ alg: str,
26
+ password: bytes | None = None,
27
+ ) -> str:
28
+ """Sign JWT parts using the specified algorithm."""
29
+ # Prepare signing input
30
+ header_b64 = b64url_encode(json.dumps(header).encode())
31
+ payload_b64 = b64url_encode(json.dumps(payload).encode())
32
+ signing_input = f"{header_b64}.{payload_b64}".encode()
33
+
34
+ # Get algorithm and sign
35
+ algorithm = get_algorithm(alg)
36
+ signature = algorithm.sign(signing_input, key, alg, password)
37
+
38
+ # Return complete JWT
39
+ signature_b64 = b64url_encode(signature)
40
+ return f"{header_b64}.{payload_b64}.{signature_b64}"
41
+
42
+
43
+ def sign_jwt(
44
+ payload: dict,
45
+ key: dict | bytes,
46
+ alg: str,
47
+ kid: str | None = None,
48
+ exp: int | None = None,
49
+ nbf: int | None = None,
50
+ iat: int | None = None,
51
+ password: bytes | None = None,
52
+ ) -> str:
53
+ """
54
+ Sign a JWT token with the given payload and key.
55
+
56
+ Args:
57
+ payload: The JWT payload
58
+ key: The signing key (JWK dict or raw key bytes)
59
+ alg: The signing algorithm to use
60
+ kid: Optional key ID
61
+ exp: Optional expiration time (seconds since epoch)
62
+ nbf: Optional not-before time (seconds since epoch)
63
+ iat: Optional issued-at time (seconds since epoch)
64
+ password: Optional password for encrypted keys
65
+
66
+ Returns:
67
+ The signed JWT token
68
+ """
69
+ now = int(time.time())
70
+
71
+ # Add standard claims if provided
72
+ if exp is not None:
73
+ payload["exp"] = exp
74
+ if nbf is not None:
75
+ payload["nbf"] = nbf
76
+ if iat is not None:
77
+ payload["iat"] = iat
78
+ elif "iat" not in payload:
79
+ payload["iat"] = now
80
+
81
+ header = create_jwt_header(alg, kid)
82
+ return sign_jwt_parts(header, payload, key, alg, password)
jwt/verify.py ADDED
@@ -0,0 +1,76 @@
1
+ import base64
2
+ import json
3
+ import time
4
+
5
+ import httpx
6
+ from cachetools import TTLCache, cached
7
+
8
+ from .algorithms import get_algorithm
9
+ from .exceptions import (
10
+ JWKNotFoundError,
11
+ JWTExpiredError,
12
+ JWTInvalidFormatError,
13
+ JWTInvalidSignatureError,
14
+ JWTIssuedInFutureError,
15
+ JWTNotValidYetError,
16
+ )
17
+
18
+
19
+ def b64url_decode(data: str) -> bytes:
20
+ padding = "=" * (-len(data) % 4)
21
+ return base64.urlsafe_b64decode(data + padding)
22
+
23
+
24
+ def extract_jwt_parts(token: str) -> tuple[dict, dict, bytes, bytes]:
25
+ try:
26
+ header_b64, payload_b64, signature_b64 = token.split(".")
27
+ header = json.loads(b64url_decode(header_b64))
28
+ payload = json.loads(b64url_decode(payload_b64))
29
+ signature = b64url_decode(signature_b64)
30
+ signing_input = f"{header_b64}.{payload_b64}".encode()
31
+ return header, payload, signature, signing_input
32
+ except (ValueError, json.JSONDecodeError) as e:
33
+ raise JWTInvalidFormatError(f"Invalid JWT format: {str(e)}")
34
+
35
+
36
+ @cached(cache=TTLCache(maxsize=1000, ttl=3600))
37
+ def fetch_jwk(kid: str, jwks_url: str) -> dict | None:
38
+ jwks = httpx.get(jwks_url).json()
39
+ for key in jwks["keys"]:
40
+ if key["kid"] == kid:
41
+ return key
42
+ raise JWKNotFoundError(f"JWK with kid '{kid}' not found")
43
+
44
+
45
+ def verify_temporal_claims(payload: dict):
46
+ now = int(time.time())
47
+ if "exp" in payload and now >= payload["exp"]:
48
+ raise JWTExpiredError("Token expired")
49
+ if "nbf" in payload and now < payload["nbf"]:
50
+ raise JWTNotValidYetError("Token not valid yet (nbf)")
51
+ if "iat" in payload and now < payload["iat"] - 60:
52
+ raise JWTIssuedInFutureError("Token issued in the future (iat)")
53
+
54
+
55
+ def verify_signature(
56
+ alg: str, key: dict, signing_input: bytes, signature: bytes
57
+ ) -> bool:
58
+ """
59
+ Verify a JWT signature using the specified algorithm and key.
60
+
61
+ Args:
62
+ alg: The algorithm used for signing
63
+ key: The verification key (JWK dict)
64
+ signing_input: The data that was signed
65
+ signature: The signature to verify
66
+
67
+ Returns:
68
+ bool: True if the signature is valid, False otherwise
69
+
70
+ Raises:
71
+ JWTInvalidSignatureError: If the signature verification fails
72
+ """
73
+ algorithm = get_algorithm(alg)
74
+ if not algorithm.verify(signing_input, key, signature):
75
+ raise JWTInvalidSignatureError("Invalid signature")
76
+ return True
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: usso-jwt
3
+ Version: 0.1.0
4
+ Summary: A simple and lightweight Python package for handling JWT (JSON Web Token) operations with USSO (Unified Single Sign-On).
5
+ Author-email: Mahdi Kiani <mahdikiany@gmail.com>
6
+ Maintainer-email: Mahdi Kiani <mahdikiany@gmail.com>
7
+ License: Copyright (c) 2016 The Python Packaging Authority (PyPA)
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
10
+ this software and associated documentation files (the "Software"), to deal in
11
+ the Software without restriction, including without limitation the rights to
12
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
13
+ of the Software, and to permit persons to whom the Software is furnished to do
14
+ so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ Project-URL: Homepage, https://github.com/ussoio/usso-jwt
28
+ Project-URL: Bug Reports, https://github.com/ussoio/usso-jwt/issues
29
+ Project-URL: Funding, https://github.com/ussoio/usso-jwt
30
+ Project-URL: Say Thanks!, https://saythanks.io/to/mahdikiani
31
+ Project-URL: Source, https://github.com/ussoio/usso-jwt
32
+ Keywords: usso,usso-jwt,sso,authentication,security,jwt,json-web-token,token
33
+ Classifier: Development Status :: 3 - Alpha
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: Topic :: Software Development :: Build Tools
36
+ Classifier: License :: OSI Approved :: MIT License
37
+ Classifier: Programming Language :: Python :: 3
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Programming Language :: Python :: 3 :: Only
42
+ Requires-Python: >=3.9
43
+ Description-Content-Type: text/markdown
44
+ License-File: LICENSE.txt
45
+ Requires-Dist: pydantic>=2
46
+ Requires-Dist: json-advanced
47
+ Requires-Dist: httpx
48
+ Requires-Dist: cryptography
49
+ Requires-Dist: cachetools>=5.0.0
50
+ Dynamic: license-file
51
+
52
+ # USSO-Client
53
+
54
+ The USSO-Client provides a universal single sign-on (SSO) integration for microservices, making it easy to add secure, scalable authentication across different frameworks. This client simplifies the process of connecting any microservice to the USSO service.
55
+
56
+ ## Features
57
+
58
+ - **Core SSO Integration**: Use the USSO core client for basic SSO functionality across any Python application.
59
+ - **Framework-Specific Modules**:
60
+ - **FastAPI Integration**: Specialized support for FastAPI applications, enabling async authentication mechanisms tailored to FastAPI's event loop.
61
+ - *Django Integration* (Coming soon): Customizable Django authentication backend that integrates seamlessly with Django's user management and middleware architecture.
62
+
63
+ ## Installation
64
+
65
+ Install the USSO client using pip:
66
+
67
+ ```bash
68
+ pip install usso
69
+ ```
70
+
71
+ To add framework-specific support, use the following commands:
72
+
73
+ For FastAPI:
74
+
75
+ ```bash
76
+ pip install "usso[fastapi]"
77
+ ```
78
+
79
+ For Django:
80
+
81
+ ```bash
82
+ pip install "usso[django]"
83
+ ```
84
+
85
+ ## Quick Start
86
+ Follow the quick start guides in the documentation to integrate USSO in your application.
87
+
88
+ ## Contributing
89
+ Contributions are welcome! See CONTRIBUTING.md for more details on how to get involved.
90
+
91
+ ## License
92
+ Distributed under the MIT License. See LICENSE for more information.
@@ -0,0 +1,17 @@
1
+ jwt/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ jwt/core.py,sha256=YGl6_-jH2ofRFmx4Y_OPL1I4uThLz7TWAI_EfO5a26E,725
3
+ jwt/exceptions.py,sha256=MYU1JcrWym9F2DRVQuuQseneFt1GZY2rggrFUCJsDho,686
4
+ jwt/jwt.py,sha256=vndYDiGgxAwtGjmaintaXCEVdLbYao8bf8-vaP3Vmes,2307
5
+ jwt/sign.py,sha256=DG9din11OohlJj-yWCTbCKvDvmVDo2JFREOC0CU7DWA,2204
6
+ jwt/verify.py,sha256=vZYsYxD7daj3OZzf492xCQ7ZlUaWDOqeHPCIFRX0AOc,2391
7
+ jwt/algorithms/__init__.py,sha256=jQAZqbsfWG9bfTlubgyStqJg6IANBFa1kJn_Gc5I1ek,846
8
+ jwt/algorithms/base.py,sha256=cM5GPnX36Am-qiWY4aUi_K4CQnTa0EtD3Ctipi1y_oA,952
9
+ jwt/algorithms/ecdsa.py,sha256=uIGb0lRu0vz_HXE-krdNFYtY5a7831H-n3pSMMg1xRY,4434
10
+ jwt/algorithms/eddsa.py,sha256=UYsCEHDLIbfsl4grsnGickCG472kYSxFZgd7cPgQm20,2720
11
+ jwt/algorithms/hmac.py,sha256=O-9hSn0o5xgbU_Bx_GCP3wQ8J-noOWYN3ZbHGb77B-M,2743
12
+ jwt/algorithms/rsa.py,sha256=9OaG76d2SY8SbuGMJcNQ2LuCsGH2q7P63LDJwLaYcgw,4958
13
+ usso_jwt-0.1.0.dist-info/licenses/LICENSE.txt,sha256=ceC9ZJOV9H6CtQDcYmHOS46NA3dHJ_WD4J9blH513pc,1081
14
+ usso_jwt-0.1.0.dist-info/METADATA,sha256=EcBRuLgkFGLzTdin7lOlywcRsUYI1pwgkcsYvflYrBk,3907
15
+ usso_jwt-0.1.0.dist-info/WHEEL,sha256=zaaOINJESkSfm_4HQVc5ssNzHCPXhJm0kEUakpsEHaU,91
16
+ usso_jwt-0.1.0.dist-info/top_level.txt,sha256=RP5DHNyJbMq2ka0FmfTgoSaQzh7e3r5XuCWCO8a00k8,4
17
+ usso_jwt-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2016 The Python Packaging Authority (PyPA)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
7
+ of the Software, and to permit persons to whom the Software is furnished to do
8
+ so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ jwt