0
# JWT Operations
1
2
Core JWT encoding and decoding functionality with comprehensive claim validation, expiration checking, and signature verification. Supports all standard JWT claims and custom payloads with flexible verification options.
3
4
## Capabilities
5
6
### JWT Encoding
7
8
Creates signed JSON Web Tokens from payload dictionaries with automatic datetime conversion and header management.
9
10
```python { .api }
11
def encode(payload: dict, key: str | bytes, algorithm: str = 'HS256',
12
headers: dict = None, json_encoder = None, sort_headers: bool = True) -> str:
13
"""
14
Encode a payload as a JSON Web Token.
15
16
Args:
17
payload (dict): Claims to encode in the token
18
key (str | bytes): Secret key or private key for signing
19
algorithm (str): Signing algorithm ('HS256', 'RS256', etc.)
20
headers (dict): Additional headers for the JWT
21
json_encoder: Custom JSON encoder class
22
sort_headers (bool): Sort header keys alphabetically
23
24
Returns:
25
str: Encoded JWT token
26
27
Raises:
28
TypeError: If payload is not a dictionary
29
InvalidKeyError: If key is invalid for algorithm
30
"""
31
```
32
33
Usage example:
34
35
```python
36
import jwt
37
from datetime import datetime, timedelta, timezone
38
39
# Simple payload
40
payload = {'user_id': 123, 'role': 'admin'}
41
token = jwt.encode(payload, 'secret', algorithm='HS256')
42
43
# With expiration and custom claims
44
payload = {
45
'user_id': 123,
46
'exp': datetime.now(tz=timezone.utc) + timedelta(hours=1),
47
'iat': datetime.now(tz=timezone.utc),
48
'aud': 'my-app',
49
'iss': 'auth-service'
50
}
51
token = jwt.encode(payload, 'secret', algorithm='HS256')
52
53
# With custom headers
54
headers = {'kid': 'key-1', 'custom': 'value'}
55
token = jwt.encode(payload, 'secret', algorithm='HS256', headers=headers)
56
```
57
58
### JWT Decoding
59
60
Decodes and validates JSON Web Tokens with comprehensive claim verification and flexible validation options.
61
62
```python { .api }
63
def decode(jwt: str | bytes, key: str | bytes = '', algorithms: list = None,
64
options: dict = None, verify: bool = None, detached_payload: bytes = None,
65
audience: str | list = None, issuer: str | list = None,
66
subject: str = None, leeway: float | timedelta = 0) -> dict:
67
"""
68
Decode and verify a JSON Web Token.
69
70
Args:
71
jwt (str | bytes): JWT token to decode
72
key (str | bytes): Secret key or public key for verification
73
algorithms (list): Allowed algorithms for verification
74
options (dict): Verification options
75
audience (str | list): Expected audience(s)
76
issuer (str | list): Expected issuer(s)
77
subject (str): Expected subject
78
leeway (float | timedelta): Clock skew tolerance in seconds
79
80
Returns:
81
dict: Decoded payload
82
83
Raises:
84
DecodeError: Token format errors
85
InvalidSignatureError: Signature verification failed
86
ExpiredSignatureError: Token has expired
87
InvalidAudienceError: Audience validation failed
88
InvalidIssuerError: Issuer validation failed
89
MissingRequiredClaimError: Required claim missing
90
"""
91
92
def decode_complete(jwt: str | bytes, key: str | bytes = '', algorithms: list = None,
93
options: dict = None, audience: str | list = None,
94
issuer: str | list = None, subject: str = None,
95
leeway: float | timedelta = 0) -> dict:
96
"""
97
Decode JWT returning header, payload, and signature.
98
99
Returns:
100
dict: {'header': dict, 'payload': dict, 'signature': bytes}
101
"""
102
```
103
104
Usage examples:
105
106
```python
107
import jwt
108
from jwt.exceptions import ExpiredSignatureError, InvalidTokenError
109
110
# Basic decoding
111
try:
112
payload = jwt.decode(token, 'secret', algorithms=['HS256'])
113
print(f"User: {payload['user_id']}")
114
except InvalidTokenError as e:
115
print(f"Invalid token: {e}")
116
117
# With claim validation
118
try:
119
payload = jwt.decode(
120
token,
121
'secret',
122
algorithms=['HS256'],
123
audience='my-app',
124
issuer='auth-service',
125
leeway=10 # 10 second clock skew tolerance
126
)
127
except ExpiredSignatureError:
128
print("Token expired")
129
except InvalidAudienceError:
130
print("Wrong audience")
131
132
# Get complete token structure
133
decoded = jwt.decode_complete(token, 'secret', algorithms=['HS256'])
134
print(f"Header: {decoded['header']}")
135
print(f"Payload: {decoded['payload']}")
136
```
137
138
### PyJWT Class
139
140
Object-oriented interface for JWT operations with configurable default options and reusable instances.
141
142
```python { .api }
143
class PyJWT:
144
def __init__(self, options: dict = None):
145
"""
146
Initialize JWT instance with default options.
147
148
Args:
149
options (dict): Default verification options
150
"""
151
152
def encode(self, payload: dict, key, algorithm: str = None,
153
headers: dict = None, json_encoder = None,
154
sort_headers: bool = True) -> str:
155
"""Encode JWT with instance options."""
156
157
def decode(self, jwt: str | bytes, key = '', algorithms: list = None,
158
options: dict = None, audience: str | list = None,
159
issuer: str | list = None, subject: str = None,
160
leeway: float | timedelta = 0) -> dict:
161
"""Decode JWT with instance options."""
162
163
def decode_complete(self, jwt: str | bytes, key = '',
164
algorithms: list = None, options: dict = None,
165
audience: str | list = None, issuer: str | list = None,
166
subject: str = None, leeway: float | timedelta = 0) -> dict:
167
"""Decode complete JWT with instance options."""
168
```
169
170
Usage example:
171
172
```python
173
# Create instance with custom defaults
174
jwt_instance = jwt.PyJWT(options={
175
'verify_exp': True,
176
'verify_aud': True,
177
'require': ['exp', 'aud']
178
})
179
180
# Use instance methods
181
token = jwt_instance.encode({'user_id': 123}, 'secret')
182
payload = jwt_instance.decode(token, 'secret', algorithms=['HS256'])
183
```
184
185
## Verification Options
186
187
The `options` dictionary controls JWT validation behavior:
188
189
```python { .api }
190
# Default verification options
191
{
192
'verify_signature': True, # Verify signature
193
'verify_exp': True, # Verify expiration time
194
'verify_nbf': True, # Verify not before time
195
'verify_iat': True, # Verify issued at time
196
'verify_aud': True, # Verify audience
197
'verify_iss': True, # Verify issuer
198
'verify_sub': True, # Verify subject
199
'verify_jti': True, # Verify JWT ID
200
'require': [] # List of required claims
201
}
202
```
203
204
Usage example:
205
206
```python
207
# Disable expiration checking
208
options = {'verify_exp': False}
209
payload = jwt.decode(token, 'secret', algorithms=['HS256'], options=options)
210
211
# Require specific claims
212
options = {'require': ['aud', 'iss', 'exp']}
213
payload = jwt.decode(token, 'secret', algorithms=['HS256'], options=options)
214
```
215
216
## Supported Algorithms
217
218
### HMAC Algorithms (Symmetric)
219
- **HS256**: HMAC using SHA-256 (default)
220
- **HS384**: HMAC using SHA-384
221
- **HS512**: HMAC using SHA-512
222
223
### RSA Algorithms (Asymmetric)
224
- **RS256**: RSASSA-PKCS1-v1_5 using SHA-256
225
- **RS384**: RSASSA-PKCS1-v1_5 using SHA-384
226
- **RS512**: RSASSA-PKCS1-v1_5 using SHA-512
227
- **PS256**: RSASSA-PSS using SHA-256
228
- **PS384**: RSASSA-PSS using SHA-384
229
- **PS512**: RSASSA-PSS using SHA-512
230
231
### ECDSA Algorithms (Asymmetric)
232
- **ES256**: ECDSA using P-256 and SHA-256
233
- **ES384**: ECDSA using P-384 and SHA-384
234
- **ES512**: ECDSA using P-521 and SHA-512
235
- **ES256K**: ECDSA using secp256k1 and SHA-256
236
237
### EdDSA Algorithms (Asymmetric)
238
- **EdDSA**: EdDSA using Ed25519 or Ed448
239
240
Note: RSA, ECDSA, and EdDSA algorithms require the `cryptography` library (`pip install PyJWT[crypto]`).