or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

algorithm-management.mdindex.mdjwk-operations.mdjwks-client.mdjws-operations.mdjwt-operations.md

index.mddocs/

0

# PyJWT

1

2

A comprehensive Python library for JSON Web Token (JWT) implementation providing secure token-based authentication and authorization. PyJWT supports complete RFC 7519 standard with encoding, decoding, and validation using various cryptographic algorithms including HMAC, RSA, ECDSA, and EdDSA signatures.

3

4

## Package Information

5

6

- **Package Name**: PyJWT

7

- **Language**: Python

8

- **Installation**: `pip install PyJWT` (basic HMAC) or `pip install PyJWT[crypto]` (full cryptographic support)

9

10

## Core Imports

11

12

```python

13

import jwt

14

```

15

16

Common usage imports:

17

18

```python

19

from jwt import encode, decode, PyJWT

20

from jwt.exceptions import InvalidTokenError, ExpiredSignatureError

21

```

22

23

## Basic Usage

24

25

```python

26

import jwt

27

from datetime import datetime, timedelta, timezone

28

29

# Encode a JWT

30

payload = {

31

'user_id': 123,

32

'exp': datetime.now(tz=timezone.utc) + timedelta(hours=1)

33

}

34

token = jwt.encode(payload, 'your-secret-key', algorithm='HS256')

35

36

# Decode and verify a JWT

37

try:

38

decoded = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])

39

print(f"User ID: {decoded['user_id']}")

40

except jwt.ExpiredSignatureError:

41

print("Token has expired")

42

except jwt.InvalidTokenError:

43

print("Invalid token")

44

```

45

46

## Architecture

47

48

PyJWT provides a layered architecture for JWT operations:

49

50

- **JWT Layer**: High-level JWT encoding/decoding with claim validation (PyJWT class)

51

- **JWS Layer**: Lower-level JSON Web Signature operations (PyJWS class)

52

- **JWK Layer**: JSON Web Key handling and cryptographic key abstraction (PyJWK, PyJWKSet)

53

- **JWKS Client**: HTTP client for fetching and caching remote key sets (PyJWKClient)

54

- **Algorithm Support**: Pluggable cryptographic algorithm system with HMAC, RSA, ECDSA, EdDSA

55

56

This design enables secure token operations across web frameworks, API services, and microservices with comprehensive claim validation, flexible key management, and extensive algorithm support.

57

58

## Capabilities

59

60

### JWT Operations

61

62

Core JWT encoding and decoding functionality with automatic claim validation, expiration checking, and signature verification. Supports standard claims (exp, nbf, iat, aud, iss, sub) and custom payloads.

63

64

```python { .api }

65

def encode(payload: dict, key: str | bytes, algorithm: str = 'HS256',

66

headers: dict = None, json_encoder = None) -> str: ...

67

def decode(jwt: str | bytes, key: str | bytes = '', algorithms: list = None,

68

options: dict = None, audience: str = None, issuer: str = None,

69

leeway: float = 0) -> dict: ...

70

class PyJWT:

71

def __init__(self, options: dict = None): ...

72

def encode(self, payload: dict, key, algorithm: str = None,

73

headers: dict = None) -> str: ...

74

def decode(self, jwt: str | bytes, key = '', algorithms: list = None,

75

options: dict = None) -> dict: ...

76

```

77

78

[JWT Operations](./jwt-operations.md)

79

80

### JWS Operations

81

82

Lower-level JSON Web Signature operations for signing and verifying arbitrary payloads. Provides direct access to the signature layer without JWT-specific claim validation.

83

84

```python { .api }

85

class PyJWS:

86

def __init__(self, algorithms: list = None, options: dict = None): ...

87

def encode(self, payload: bytes, key, algorithm: str = None,

88

headers: dict = None) -> str: ...

89

def decode(self, jws: str | bytes, key = '', algorithms: list = None,

90

options: dict = None) -> bytes: ...

91

def get_unverified_header(self, jwt: str | bytes) -> dict: ...

92

```

93

94

[JWS Operations](./jws-operations.md)

95

96

### JSON Web Keys (JWK)

97

98

JSON Web Key handling and cryptographic key abstraction supporting RSA, ECDSA, EdDSA, and symmetric keys. Provides key parsing, validation, and algorithm detection.

99

100

```python { .api }

101

class PyJWK:

102

def __init__(self, jwk_data: dict, algorithm: str = None): ...

103

@staticmethod

104

def from_dict(obj: dict, algorithm: str = None) -> 'PyJWK': ...

105

@staticmethod

106

def from_json(data: str, algorithm: str = None) -> 'PyJWK': ...

107

@property

108

def key_type(self) -> str: ...

109

@property

110

def key_id(self) -> str: ...

111

112

class PyJWKSet:

113

def __init__(self, keys: list): ...

114

@staticmethod

115

def from_dict(obj: dict) -> 'PyJWKSet': ...

116

@staticmethod

117

def from_json(data: str) -> 'PyJWKSet': ...

118

def __getitem__(self, kid: str) -> PyJWK: ...

119

```

120

121

[JSON Web Keys](./jwk-operations.md)

122

123

### JWKS Client

124

125

HTTP client for fetching and caching JSON Web Key Sets from remote endpoints. Supports automatic key refresh, caching strategies, and integration with JWT verification.

126

127

```python { .api }

128

class PyJWKClient:

129

def __init__(self, uri: str, cache_keys: bool = False,

130

max_cached_keys: int = 16, cache_jwk_set: bool = True,

131

lifespan: int = 300, headers: dict = None,

132

timeout: int = 30): ...

133

def get_signing_key(self, kid: str) -> PyJWK: ...

134

def get_signing_key_from_jwt(self, token: str) -> PyJWK: ...

135

def get_jwk_set(self, refresh: bool = False) -> PyJWKSet: ...

136

```

137

138

[JWKS Client](./jwks-client.md)

139

140

### Algorithm Management

141

142

Cryptographic algorithm registration and management system supporting custom algorithms and algorithm whitelisting for security.

143

144

```python { .api }

145

def register_algorithm(alg_id: str, alg_obj) -> None: ...

146

def unregister_algorithm(alg_id: str) -> None: ...

147

def get_algorithm_by_name(alg_name: str): ...

148

def get_unverified_header(jwt: str | bytes) -> dict: ...

149

```

150

151

[Algorithm Management](./algorithm-management.md)

152

153

## Exception Types

154

155

```python { .api }

156

class PyJWTError(Exception):

157

"""Base class for all PyJWT exceptions"""

158

159

class InvalidTokenError(PyJWTError):

160

"""Invalid token format or structure"""

161

162

class DecodeError(InvalidTokenError):

163

"""Token parsing or decoding errors"""

164

165

class InvalidSignatureError(DecodeError):

166

"""Signature verification failed"""

167

168

class ExpiredSignatureError(InvalidTokenError):

169

"""Token has expired (exp claim)"""

170

171

class ImmatureSignatureError(InvalidTokenError):

172

"""Token not yet valid (nbf/iat claims)"""

173

174

class InvalidAudienceError(InvalidTokenError):

175

"""Audience claim validation failed"""

176

177

class InvalidIssuerError(InvalidTokenError):

178

"""Issuer claim validation failed"""

179

180

class MissingRequiredClaimError(InvalidTokenError):

181

"""Required claim missing from token"""

182

183

class InvalidSubjectError(InvalidTokenError):

184

"""Subject claim validation failed"""

185

186

class InvalidJTIError(InvalidTokenError):

187

"""JWT ID claim validation failed"""

188

189

class PyJWKError(PyJWTError):

190

"""JSON Web Key related errors"""

191

192

class MissingCryptographyError(PyJWKError):

193

"""Cryptography library required for asymmetric algorithms"""

194

195

class PyJWKClientError(PyJWTError):

196

"""JWKS client errors"""

197

```