Debian Codegraph @

docs/usage.rst

raw
1 Usage Examples
2 ==============
3
4 Encoding & Decoding Tokens with HS256
5 -------------------------------------
6
7 .. code-block:: pycon
8
9 >>> import jwt
10 >>> key = "secret"
11 >>> encoded = jwt.encode({"some": "payload"}, key, algorithm="HS256")
12 >>> jwt.decode(encoded, key, algorithms="HS256")
13 {'some': 'payload'}
14
15 Encoding & Decoding Tokens with RS256 (RSA)
16 -------------------------------------------
17
18 RSA encoding and decoding require the ``cryptography`` module. See :ref:`installation_cryptography`.
19
20 .. code-block:: pycon
21
22 >>> import jwt
23 >>> private_key = b"-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAwhvqCC+37A+UXgcvDl+7nbVjDI3QErdZBkI1VypVBMkKKWHM\nNLMdHk0bIKL+1aDYTRRsCKBy9ZmSSX1pwQlO/3+gRs/MWG27gdRNtf57uLk1+lQI\n6hBDozuyBR0YayQDIx6VsmpBn3Y8LS13p4pTBvirlsdX+jXrbOEaQphn0OdQo0WD\noOwwsPCNCKoIMbUOtUCowvjesFXlWkwG1zeMzlD1aDDS478PDZdckPjT96ICzqe4\nO1Ok6fRGnor2UTmuPy0f1tI0F7Ol5DHAD6pZbkhB70aTBuWDGLDR0iLenzyQecmD\n4aU19r1XC9AHsVbQzxHrP8FveZGlV/nJOBJwFwIDAQABAoIBAFCVFBA39yvJv/dV\nFiTqe1HahnckvFe4w/2EKO65xTfKWiyZzBOotBLrQbLH1/FJ5+H/82WVboQlMATQ\nSsH3olMRYbFj/NpNG8WnJGfEcQpb4Vu93UGGZP3z/1B+Jq/78E15Gf5KfFm91PeQ\nY5crJpLDU0CyGwTls4ms3aD98kNXuxhCGVbje5lCARizNKfm/+2qsnTYfKnAzN+n\nnm0WCjcHmvGYO8kGHWbFWMWvIlkoZ5YubSX2raNeg+YdMJUHz2ej1ocfW0A8/tmL\nwtFoBSuBe1Z2ykhX4t6mRHp0airhyc+MO0bIlW61vU/cPGPos16PoS7/V08S7ZED\nX64rkyECgYE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DYTRRsCKBy9ZmSSX1pwQlO\n/3+gRs/MWG27gdRNtf57uLk1+lQI6hBDozuyBR0YayQDIx6VsmpBn3Y8LS13p4pT\nBvirlsdX+jXrbOEaQphn0OdQo0WDoOwwsPCNCKoIMbUOtUCowvjesFXlWkwG1zeM\nzlD1aDDS478PDZdckPjT96ICzqe4O1Ok6fRGnor2UTmuPy0f1tI0F7Ol5DHAD6pZ\nbkhB70aTBuWDGLDR0iLenzyQecmD4aU19r1XC9AHsVbQzxHrP8FveZGlV/nJOBJw\nFwIDAQAB\n-----END PUBLIC KEY-----\n"
25 >>> encoded = jwt.encode({"some": "payload"}, private_key, algorithm="RS256")
26 >>> jwt.decode(encoded, public_key, algorithms=["RS256"])
27 {'some': 'payload'}
28
29 If your private key needs a passphrase, you need to pass in a ``PrivateKey`` object from ``cryptography``.
30
31 .. code-block:: python
32
33 from cryptography.hazmat.primitives import serialization
34 from cryptography.hazmat.backends import default_backend
35
36 pem_bytes = b"-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,C9C8F89EC68D15F26EB9B9695216C6DC\nE3lvX0dYjDxC0DIDitwNj+mEvU48Cqlp9esIeVmfcFmM6KpuQEA4asg/19kldbRq\ntOAYwmMuzz6GNYtX6sQXcStUE3pKMiMaTuP9WXzTc0boSYsGpGoQLtGv3h+0lkPu\nTGaktEhIfplAYlmsS/twr9Jh9QZjEs3dEMwpuF8A/iDZFeIE2thZL0bo38VWorgZ\nTCoOlC7qGtaeDvXXYrMvAUw3lN9A+DvxuPvbGqfqiHVBhxRcQEcR5p65lKP/V0WQ\nDe0AqCx1ghYGnExT7I4GLfr7Ux3F1UcVldPPsNeCTR/5YMOYDw7o5CZZ2TM39T33\nDBwfRhDqKe4bMUQcvcD54S2tfW7tEekm6mx5JwzW11sd0Gprj2uggDTOj3ce2yzM\nzl/dfbyFgh6v4jFeblIgvQ4VPg9nfCaRhatw5KXnfHBvmvdxlQ1Qp5P43ThXj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c2Hdoj5dMa6T7ysIwZGEissJ/MEP+dpRs7VmCjWrHCDHfeAIO0n32g4zbzlNc/OA\nIdCXTvi4xUEn2n3JPt5Ba9qDUevaHSERlLxI+9a4ZaZeg4t+AzY0ur6+RWx+PaXB\n-----END RSA PRIVATE KEY-----\n"
37 passphrase = b"abc123"
38
39 private_key = serialization.load_pem_private_key(
40 pem_bytes, password=passphrase, backend=default_backend()
41 )
42 encoded = jwt.encode({"some": "payload"}, private_key, algorithm="RS256")
43
44 If you are repeatedly encoding with the same private key, reusing the same
45 ``RSAPrivateKey`` also has performance benefits because it avoids the
46 CPU-intensive ``RSA_check_key`` primality test.
47
48 Encoding & Decoding Tokens with PS256 (RSA)
49 -------------------------------------------
50
51 RSA encoding and decoding require the ``cryptography`` module. See :ref:`installation_cryptography`.
52
53 .. code-block:: pycon
54
55 >>> import jwt
56 >>> private_key = "-----BEGIN RSA PRIVATE KEY-----\nMIIEogIBAAKCAQEAuNhCS6bodtd+PvKqNj+tYZYqTNMDkf0rcptgHhecSsMP9Vay\n+6NvJk1tC+IajPaE4yRJVY4jFqEt3A0MJ9sKe5mWDYFmzW/L6VzQvQ+0nrMc1YTE\nDpOf7BQhlW5W0mDj5SwSR50Lxg/acb+SMWq6zmhuAoLRapH17K2RWONA2vr2frox\nJ6N9TGtrQHygDb0p9D6jPnXEe4y+zBuj6o0bCkJgCVNM+CU19xBepj5caetYV28/\n49yl5XPi93n1ATU+7aGAKxuvjudODuHhF/UsZScMFSHeZW367eQldTB2w9uoIIzW\nO46tKimr21zYifMimjwnBQ/PLDqc7HqY0Y/rLQIDAQABAoIBAAdu0CD7/Iu61/LE\nDfV8fgZXOYA5WVgSLCBsVbh1Y+2FsStBFJVrLwRanLCbo6GuJWMqNGC3ryWGebJI\nPAg7lfepEhBHodClAY1yvq9mOvHJa2Fn+KegEWWMMbAxQwCBW5NS6waXhBUE0i3n\ncYOB3TKA9IYuqH52kW22VQqT/imlWEb28pJJT49YfggmOOtAkrKerokO53lAfr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 >>> public_key = "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuNhCS6bodtd+PvKqNj+t\nYZYqTNMDkf0rcptgHhecSsMP9Vay+6NvJk1tC+IajPaE4yRJVY4jFqEt3A0MJ9sK\ne5mWDYFmzW/L6VzQvQ+0nrMc1YTEDpOf7BQhlW5W0mDj5SwSR50Lxg/acb+SMWq6\nzmhuAoLRapH17K2RWONA2vr2froxJ6N9TGtrQHygDb0p9D6jPnXEe4y+zBuj6o0b\nCkJgCVNM+CU19xBepj5caetYV28/49yl5XPi93n1ATU+7aGAKxuvjudODuHhF/Us\nZScMFSHeZW367eQldTB2w9uoIIzWO46tKimr21zYifMimjwnBQ/PLDqc7HqY0Y/r\nLQIDAQAB\n-----END PUBLIC KEY-----\n"
58 >>> encoded = jwt.encode({"some": "payload"}, private_key, algorithm="PS256")
59 >>> jwt.decode(encoded, public_key, algorithms=["PS256"])
60 {'some': 'payload'}
61
62 Encoding & Decoding Tokens with EdDSA (Ed25519)
63 -----------------------------------------------
64
65 EdDSA encoding and decoding require the ``cryptography`` module. See :ref:`installation_cryptography`.
66
67 .. code-block:: pycon
68
69 >>> import jwt
70 >>> private_key = "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIPtUxyxlhjOWetjIYmc98dmB2GxpeaMPP64qBhZmG13r\n-----END PRIVATE KEY-----\n"
71 >>> public_key = "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA7p4c1IU6aA65FWn6YZ+Bya5dRbfd4P6d4a6H0u9+gCg=\n-----END PUBLIC KEY-----\n"
72 >>> encoded = jwt.encode({"some": "payload"}, private_key, algorithm="EdDSA")
73 >>> jwt.decode(encoded, public_key, algorithms=["EdDSA"])
74 {'some': 'payload'}
75
76 Encoding & Decoding Tokens with ES256 (ECDSA)
77 ---------------------------------------------
78
79 ECDSA encoding and decoding require the ``cryptography`` module. See :ref:`installation_cryptography`.
80
81 .. code-block:: pycon
82
83 >>> import jwt
84 >>> private_key = b"-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIHAhM7P6HG3LgkDvgvfDeaMA6uELj+jEKWsSeOpS/SfYoAoGCCqGSM49\nAwEHoUQDQgAEXHVxB7s5SR7I9cWwry/JkECIRekaCwG3uOLCYbw5gVzn4dRmwMyY\nUJFcQWuFSfECRK+uQOOXD0YSEucBq0p5tA==\n-----END EC PRIVATE KEY-----\n"
85 >>> public_key = b"-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEXHVxB7s5SR7I9cWwry/JkECIReka\nCwG3uOLCYbw5gVzn4dRmwMyYUJFcQWuFSfECRK+uQOOXD0YSEucBq0p5tA==\n-----END PUBLIC KEY-----\n"
86 >>> encoded = jwt.encode({"some": "payload"}, private_key, algorithm="ES256")
87 >>> jwt.decode(encoded, public_key, algorithms=["ES256"])
88 {'some': 'payload'}
89
90
91 Specifying Additional Headers
92 -----------------------------
93
94 .. code-block:: pycon
95
96 >>> jwt.encode(
97 ... {"some": "payload"},
98 ... "secret",
99 ... algorithm="HS256",
100 ... headers={"kid": "230498151c214b788dd97f22b85410a5"},
101 ... )
102 'eyJhbGciOiJIUzI1NiIsImtpZCI6IjIzMDQ5ODE1MWMyMTRiNzg4ZGQ5N2YyMmI4NTQxMGE1IiwidHlwIjoiSldUIn0.eyJzb21lIjoicGF5bG9hZCJ9.0n16c-shKKnw6gervyk1Dge35tvzbzQ_KCV3H3bgoJ0'
103
104
105 By default the ``typ`` is attaching to the headers. In case when you don't need to pass this header to the token, you have to explicitly null it.
106
107 .. code-block:: pycon
108
109 >>> jwt.encode(
110 ... {"some": "payload"},
111 ... "secret",
112 ... algorithm="HS256",
113 ... headers={"typ": None},
114 ... ) # doctest: +ELLIPSIS
115 'eyJhbGciOiJIUzI1NiJ9.eyJzb21lIjoicGF5bG9hZCJ9...'
116
117 Reading the Claimset without Validation
118 ---------------------------------------
119
120 If you wish to read the claimset of a JWT without performing validation of the
121 signature or any of the registered claim names, you can set the
122 ``verify_signature`` option to ``False``.
123
124 Note: It is generally ill-advised to use this functionality unless you
125 clearly understand what you are doing. Without digital signature information,
126 the integrity or authenticity of the claimset cannot be trusted.
127
128 .. code-block:: pycon
129
130 >>> jwt.decode(encoded, options={"verify_signature": False})
131 {'some': 'payload'}
132
133 Reading Headers without Validation
134 ----------------------------------
135
136 Some APIs require you to read a JWT header without validation. For example,
137 in situations where the token issuer uses multiple keys and you have no
138 way of knowing in advance which one of the issuer's public keys or shared
139 secrets to use for validation, the issuer may include an identifier for the
140 key in the header.
141
142 .. code-block:: pycon
143
144 >>> encoded = jwt.encode(
145 ... {"some": "payload"},
146 ... "secret",
147 ... algorithm="HS256",
148 ... headers={"kid": "230498151c214b788dd97f22b85410a5"},
149 ... )
150 >>> jwt.get_unverified_header(encoded)
151 {'alg': 'HS256', 'kid': '230498151c214b788dd97f22b85410a5', 'typ': 'JWT'}
152
153 Registered Claim Names
154 ----------------------
155
156 The JWT specification defines some registered claim names and defines
157 how they should be used. PyJWT supports these registered claim names:
158
159 - "exp" (Expiration Time) Claim
160 - "nbf" (Not Before Time) Claim
161 - "iss" (Issuer) Claim
162 - "aud" (Audience) Claim
163 - "iat" (Issued At) Claim
164 - "sub" (Subject) Claim
165 - "jti" (JWT ID) Claim
166
167 Expiration Time Claim (exp)
168 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
169
170 The "exp" (expiration time) claim identifies the expiration time on
171 or after which the JWT MUST NOT be accepted for processing. The
172 processing of the "exp" claim requires that the current date/time
173 MUST be before the expiration date/time listed in the "exp" claim.
174 Implementers MAY provide for some small leeway, usually no more than
175 a few minutes, to account for clock skew. Its value MUST be a number
176 containing a NumericDate value. Use of this claim is OPTIONAL.
177
178 You can pass the expiration time as a UTC UNIX timestamp (an int) or as a
179 datetime, which will be converted into an int. For example:
180
181 .. code-block:: pycon
182
183 >>> from datetime import datetime, timezone
184 >>> token = jwt.encode({"exp": 1371720939}, "secret")
185 >>> token = jwt.encode({"exp": datetime.now(tz=timezone.utc)}, "secret")
186
187 Expiration time is automatically verified in `jwt.decode()` and raises
188 `jwt.ExpiredSignatureError` if the expiration time is in the past:
189
190 .. code-block:: pycon
191
192 >>> try:
193 ... jwt.decode(token, "secret", algorithms=["HS256"])
194 ... except jwt.ExpiredSignatureError:
195 ... print("expired")
196 ...
197 expired
198
199 Expiration time will be compared to the current UTC time (as given by
200 `timegm(datetime.now(tz=timezone.utc).utctimetuple())`), so be sure to use a UTC timestamp
201 or datetime in encoding.
202
203 You can turn off expiration time verification with the `verify_exp` parameter in the options argument.
204
205 PyJWT also supports the leeway part of the expiration time definition, which
206 means you can validate a expiration time which is in the past but not very far.
207 For example, if you have a JWT payload with a expiration time set to 30 seconds
208 after creation but you know that sometimes you will process it after 30 seconds,
209 you can set a leeway of 5 seconds in order to have some margin:
210
211 .. code-block:: pycon
212
213 >>> import time, datetime
214 >>> from datetime import timezone
215 >>> payload = {
216 ... "exp": datetime.datetime.now(tz=timezone.utc) + datetime.timedelta(seconds=1)
217 ... }
218 >>> token = jwt.encode(payload, "secret")
219 >>> time.sleep(2)
220 >>> # JWT payload is now expired
221 >>> # But with some leeway, it will still validate
222 >>> decoded = jwt.decode(token, "secret", leeway=5, algorithms=["HS256"])
223
224 Instead of specifying the leeway as a number of seconds, a `datetime.timedelta`
225 instance can be used. The last line in the example above is equivalent to:
226
227 .. code-block:: pycon
228
229 >>> decoded = jwt.decode(
230 ... token, "secret", leeway=datetime.timedelta(seconds=5), algorithms=["HS256"]
231 ... )
232
233 Not Before Time Claim (nbf)
234 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
235
236 The "nbf" (not before) claim identifies the time before which the JWT
237 MUST NOT be accepted for processing. The processing of the "nbf"
238 claim requires that the current date/time MUST be after or equal to
239 the not-before date/time listed in the "nbf" claim. Implementers MAY
240 provide for some small leeway, usually no more than a few minutes, to
241 account for clock skew. Its value MUST be a number containing a
242 NumericDate value. Use of this claim is OPTIONAL.
243
244 The `nbf` claim works similarly to the `exp` claim above.
245
246 .. code-block:: pycon
247
248 >>> token = jwt.encode({"nbf": 1371720939}, "secret")
249 >>> token = jwt.encode({"nbf": datetime.datetime.now(tz=timezone.utc)}, "secret")
250
251 The `nbf` claim also supports the leeway feature similar to the `exp` claim. This
252 allows you to validate a “not before” time that is slightly in the future. Using
253 leeway with the nbf claim can be particularly helpful in scenarios where clock
254 synchronization between the token issuer and the validator is imprecise.
255
256 .. code-block:: pycon
257
258 >>> import time, datetime
259 >>> from datetime import timezone
260 >>> payload = {
261 ... "nbf": datetime.datetime.now(tz=timezone.utc) - datetime.timedelta(seconds=3)
262 ... }
263 >>> token = jwt.encode(payload, "secret")
264 >>> # JWT payload is not valid yet
265 >>> # But with some leeway, it will still validate
266 >>> decoded = jwt.decode(token, "secret", leeway=5, algorithms=["HS256"])
267
268
269 Issuer Claim (iss)
270 ~~~~~~~~~~~~~~~~~~
271
272 The "iss" (issuer) claim identifies the principal that issued the
273 JWT. The processing of this claim is generally application specific.
274 The "iss" value is a case-sensitive string containing a StringOrURI
275 value. Use of this claim is OPTIONAL.
276
277 .. code-block:: pycon
278
279 >>> payload = {"some": "payload", "iss": "urn:foo"}
280 >>> token = jwt.encode(payload, "secret")
281 >>> try:
282 ... jwt.decode(token, "secret", issuer="urn:invalid", algorithms=["HS256"])
283 ... except jwt.InvalidIssuerError:
284 ... print("invalid issuer")
285 ...
286 invalid issuer
287
288 If the issuer claim is incorrect, `jwt.InvalidIssuerError` will be raised.
289
290 Audience Claim (aud)
291 ~~~~~~~~~~~~~~~~~~~~
292
293 The "aud" (audience) claim identifies the recipients that the JWT is
294 intended for. Each principal intended to process the JWT MUST
295 identify itself with a value in the audience claim. If the principal
296 processing the claim does not identify itself with a value in the
297 "aud" claim when this claim is present, then the JWT MUST be
298 rejected.
299
300 In the general case, the "aud" value is an array of case-
301 sensitive strings, each containing a StringOrURI value.
302
303 .. code-block:: pycon
304
305 >>> payload = {"some": "payload", "aud": ["urn:foo", "urn:bar"]}
306 >>> token = jwt.encode(payload, "secret")
307 >>> decoded = jwt.decode(token, "secret", audience="urn:foo", algorithms=["HS256"])
308 >>> decoded = jwt.decode(token, "secret", audience="urn:bar", algorithms=["HS256"])
309
310 In the special case when the JWT has one audience, the "aud" value MAY be
311 a single case-sensitive string containing a StringOrURI value.
312
313 .. code-block:: pycon
314
315 >>> payload = {"some": "payload", "aud": "urn:foo"}
316 >>> token = jwt.encode(payload, "secret")
317 >>> decoded = jwt.decode(token, "secret", audience="urn:foo", algorithms=["HS256"])
318
319 If multiple audiences are accepted, the ``audience`` parameter for
320 ``jwt.decode`` can also be an iterable
321
322 .. code-block:: pycon
323
324 >>> payload = {"some": "payload", "aud": "urn:foo"}
325 >>> token = jwt.encode(payload, "secret")
326 >>> decoded = jwt.decode(
327 ... token, "secret", audience=["urn:foo", "urn:bar"], algorithms=["HS256"]
328 ... )
329 >>> try:
330 ... jwt.decode(token, "secret", audience=["urn:invalid"], algorithms=["HS256"])
331 ... except jwt.InvalidAudienceError:
332 ... print("invalid audience")
333 ...
334 invalid audience
335
336 The interpretation of audience values is generally application specific.
337 Use of this claim is OPTIONAL.
338
339 If the audience claim is incorrect, `jwt.InvalidAudienceError` will be raised.
340
341 Issued At Claim (iat)
342 ~~~~~~~~~~~~~~~~~~~~~
343
344 The iat (issued at) claim identifies the time at which the JWT was issued.
345 This claim can be used to determine the age of the JWT. Its value MUST be a
346 number containing a NumericDate value. Use of this claim is OPTIONAL.
347
348 If the `iat` claim is not a number, an `jwt.InvalidIssuedAtError` exception will be raised.
349
350 .. code-block:: pycon
351
352 >>> token = jwt.encode({"iat": 1371720939}, "secret")
353 >>> token = jwt.encode({"iat": datetime.datetime.now(tz=timezone.utc)}, "secret")
354
355 Subject Claim (sub)
356 ~~~~~~~~~~~~~~~~~~~
357
358 The "sub" (subject) claim identifies the principal that is the subject of the JWT.
359 The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique.
360 Use of this claim is OPTIONAL.
361
362 .. code-block:: pycon
363
364 >>> payload = {"some": "payload", "sub": "1234567890"}
365 >>> token = jwt.encode(payload, "secret")
366 >>> decoded = jwt.decode(token, "secret", algorithms=["HS256"])
367 >>> decoded["sub"]
368 '1234567890'
369
370 Think of the `sub` claim as the **"who"** of the JWT.
371 It identifies the subject of the token — the user or entity that the token is about.
372 The claims inside a JWT are essentially statements about this subject.
373
374 For example, if you have a JWT for a logged-in user, the `sub` claim would typically be their unique user ID, like `1234567890`.
375 This value needs to be unique within your application's context so you can reliably identify who the token belongs to.
376 While the `sub` claim is optional, it's a fundamental part of most JWT-based authentication systems.
377
378 JWT ID Claim (jti)
379 ~~~~~~~~~~~~~~~~~~
380
381 The "jti" (JWT ID) claim provides a unique identifier for the JWT.
382 The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object.
383 If the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well.
384 The "jti" value is a case-sensitive string.
385 Use of this claim is OPTIONAL.
386
387 .. code-block:: pycon
388
389 >>> import uuid
390 >>> payload = {"some": "payload", "jti": str(uuid.uuid4())}
391 >>> token = jwt.encode(payload, "secret")
392 >>> decoded = jwt.decode(token, "secret", algorithms=["HS256"])
393 >>> decoded["jti"] # doctest: +SKIP
394 '3fa85f64-5717-4562-b3fc-2c963f66afa6'
395
396 The `jti` claim is giving your JWT a unique identifier.
397 Think of it like a serial number for the token.
398 This ID must be assigned in a way that makes it virtually impossible for two different tokens to have the same `jti` value.
399 A common practice is to use a Universally Unique Identifier (UUID).
400
401 The `jti` claim is used to **prevent replay attacks**.
402 A replay attack happens when a bad actor intercepts a valid token and uses it to make a request again.
403 By storing the `jti` of every token you've already processed in a database or cache, you can check if a token has been used before.
404 If a token with a previously-seen `jti` shows up, you can reject the request, stopping the attack.
405
406
407 .. _key-length-validation:
408
409 Key Length Validation
410 ---------------------
411
412 PyJWT validates that cryptographic keys meet minimum recommended lengths.
413 By default, a warning (``InsecureKeyLengthWarning``) is emitted when a key
414 is too short. You can configure PyJWT to raise an ``InvalidKeyError`` instead.
415
416 The minimum key lengths are:
417
418 * **HMAC** (HS256, HS384, HS512): Key must be at least as long as the hash
419 output (32, 48, or 64 bytes respectively), per `RFC 7518 Section 3.2
420 <https://www.rfc-editor.org/rfc/rfc7518#section-3.2>`_.
421 * **RSA** (RS256, RS384, RS512, PS256, PS384, PS512): Key must be at least
422 2048 bits, per `NIST SP 800-131A
423 <https://csrc.nist.gov/publications/detail/sp/800-131a/rev-2/final>`_.
424
425 By default, short keys produce an ``InsecureKeyLengthWarning``:
426
427 .. code-block:: pycon
428
429 >>> import jwt
430 >>> encoded = jwt.encode({"some": "payload"}, "short", algorithm="HS256")
431
432 To enforce minimum key lengths (raise ``InvalidKeyError`` on short keys),
433 pass ``enforce_minimum_key_length=True`` in the options when creating a
434 ``PyJWT`` or ``PyJWS`` instance:
435
436 .. code-block:: pycon
437
438 >>> strict_jwt = jwt.PyJWT(options={"enforce_minimum_key_length": True})
439 >>> try:
440 ... strict_jwt.encode({"some": "payload"}, "short", algorithm="HS256")
441 ... except jwt.InvalidKeyError:
442 ... print("key too short")
443 ...
444 key too short
445
446 To suppress the warning without enforcing, use Python's standard
447 ``warnings`` module:
448
449 .. code-block:: python
450
451 import warnings
452 import jwt
453
454 warnings.filterwarnings("ignore", category=jwt.InsecureKeyLengthWarning)
455
456 Requiring Presence of Claims
457 ----------------------------
458
459 If you wish to require one or more claims to be present in the claimset, you can set the ``require`` parameter to include these claims.
460
461 .. code-block:: pycon
462
463 >>> token = jwt.encode({"sub": "1234567890", "iat": 1371720939}, "secret")
464 >>> try:
465 ... jwt.decode(
466 ... token,
467 ... "secret",
468 ... options={"require": ["exp", "iss", "sub"]},
469 ... algorithms=["HS256"],
470 ... )
471 ... except jwt.MissingRequiredClaimError as e:
472 ... print(e)
473 ...
474 Token is missing the "exp" claim
475
476 Retrieve RSA signing keys from a JWKS endpoint
477 ----------------------------------------------
478
479 ``PyJWKClient`` fetches and manages JSON Web Key Sets (JWKS) from a remote
480 endpoint. Identity providers such as Auth0, Okta, and any OpenID Connect server
481 publish a JWKS endpoint containing the public keys used to sign JWTs. Instead
482 of hard-coding public keys, you can point ``PyJWKClient`` at that URL and let
483 it resolve the correct key for each token automatically.
484
485 Pass the JWKS URL to create a client, then call
486 ``get_signing_key_from_jwt()`` with a token to look up the matching key by its
487 ``kid`` header claim:
488
489 .. code-block:: pycon
490
491 >>> import jwt
492 >>> from jwt import PyJWKClient
493 >>> token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik5FRTFRVVJCT1RNNE16STVSa0ZETlRZeE9UVTFNRGcyT0Rnd1EwVXpNVGsxUWpZeVJrUkZRdyJ9.eyJpc3MiOiJodHRwczovL2Rldi04N2V2eDlydS5hdXRoMC5jb20vIiwic3ViIjoiYVc0Q2NhNzl4UmVMV1V6MGFFMkg2a0QwTzNjWEJWdENAY2xpZW50cyIsImF1ZCI6Imh0dHBzOi8vZXhwZW5zZXMtYXBpIiwiaWF0IjoxNTcyMDA2OTU0LCJleHAiOjE1NzIwMDY5NjQsImF6cCI6ImFXNENjYTc5eFJlTFdVejBhRTJINmtEME8zY1hCVnRDIiwiZ3R5IjoiY2xpZW50LWNyZWRlbnRpYWxzIn0.PUxE7xn52aTCohGiWoSdMBZGiYAHwE5FYie0Y1qUT68IHSTXwXVd6hn02HTah6epvHHVKA2FqcFZ4GGv5VTHEvYpeggiiZMgbxFrmTEY0csL6VNkX1eaJGcuehwQCRBKRLL3zKmA5IKGy5GeUnIbpPHLHDxr-GXvgFzsdsyWlVQvPX2xjeaQ217r2PtxDeqjlf66UYl6oY6AqNS8DH3iryCvIfCcybRZkc_hdy-6ZMoKT6Piijvk_aXdm7-QQqKJFHLuEqrVSOuBqqiNfVrG27QzAPuPOxvfXTVLXL2jek5meH6n-VWgrBdoMFH93QEszEDowDAEhQPHVs0xj7SIzA"
494 >>> url = "https://dev-87evx9ru.auth0.com/.well-known/jwks.json"
495 >>> optional_custom_headers = {"User-agent": "custom-user-agent"}
496 >>> jwks_client = PyJWKClient(url, headers=optional_custom_headers)
497 >>> signing_key = jwks_client.get_signing_key_from_jwt(token)
498 >>> jwt.decode(
499 ... token,
500 ... signing_key,
501 ... audience="https://expenses-api",
502 ... options={"verify_exp": False},
503 ... algorithms=["RS256"],
504 ... )
505 {'iss': 'https://dev-87evx9ru.auth0.com/', 'sub': 'aW4Cca79xReLWUz0aE2H6kD0O3cXBVtC@clients', 'aud': 'https://expenses-api', 'iat': 1572006954, 'exp': 1572006964, 'azp': 'aW4Cca79xReLWUz0aE2H6kD0O3cXBVtC', 'gty': 'client-credentials'}
506
507 If the ``kid`` is not found in the current key set, ``PyJWKClient``
508 automatically refreshes the JWKS from the endpoint and retries before raising
509 an error.
510
511 ``PyJWKClient`` also includes built-in caching to avoid unnecessary network
512 requests. See :class:`~jwt.PyJWKClient` in the API reference for details on
513 the caching parameters.
514
515 OIDC Login Flow
516 ---------------
517
518 The following usage demonstrates an OIDC login flow using pyjwt. Further
519 reading about the OIDC spec is recommended for implementers.
520
521 In particular, this demonstrates validation of the ``at_hash`` claim.
522 This claim relies on data from outside of the the JWT for validation. Methods
523 are provided which support computation and validation of this claim, but it
524 is not built into pyjwt.
525
526 .. code-block:: python
527
528 import base64
529 import jwt
530 import requests
531
532 # Part 1: setup
533 # get the OIDC config and JWKs to use
534
535 # in OIDC, you must know your client_id (this is the OAuth 2.0 client_id)
536 client_id = ...
537
538 # example of fetching data from your OIDC server
539 # see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig
540 oidc_server = ...
541 oidc_config = requests.get(
542 f"https://{oidc_server}/.well-known/openid-configuration"
543 ).json()
544 signing_algos = oidc_config["id_token_signing_alg_values_supported"]
545
546 # setup a PyJWKClient to get the appropriate signing key
547 jwks_client = jwt.PyJWKClient(oidc_config["jwks_uri"])
548
549 # Part 2: login / authorization
550 # when a user completes an OIDC login flow, there will be a well-formed
551 # response object to parse/handle
552
553 # data from the login flow
554 # see: https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
555 token_response = ...
556 id_token = token_response["id_token"]
557 access_token = token_response["access_token"]
558
559 # Part 3: decode and validate at_hash
560 # after the login is complete, the id_token needs to be decoded
561 # this is the stage at which an OIDC client must verify the at_hash
562
563 # get signing_key from id_token
564 signing_key = jwks_client.get_signing_key_from_jwt(id_token)
565
566 # now, decode_complete to get payload + header
567 data = jwt.decode_complete(
568 id_token,
569 key=signing_key,
570 audience=client_id,
571 algorithms=signing_algos,
572 )
573 payload, header = data["payload"], data["header"]
574
575 # get the pyjwt algorithm object
576 alg_obj = jwt.get_algorithm_by_name(header["alg"])
577
578 # compute at_hash, then validate / assert
579 digest = alg_obj.compute_hash_digest(access_token)
580 at_hash = base64.urlsafe_b64encode(digest[: (len(digest) // 2)]).rstrip("=")
581 assert at_hash == payload["at_hash"]