File: jwt.rst

package info (click to toggle)
joserfc 1.6.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,480 kB
  • sloc: python: 8,096; makefile: 18
file content (556 lines) | stat: -rw-r--r-- 16,757 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
:description: How to encode and decode a JSON Web Token (JWT) in python.

.. _jwt:

JSON Web Token
==============

.. module:: joserfc.jwt
    :noindex:

JSON Web Token (JWT) is built on top of :ref:`jws` or :ref:`jwe` and includes
specific payload claims. These claims are required to be in JSON format and
follow a predefined set of fields.

.. hint::

    Do you know that JSON Web Token (JWT) is not a part of JOSE. Instead,
    it was created by the OAuth working group.

Encode token
------------

:meth:`encode` is the method for creating a JSON Web Token string.
It encodes the payload with the given ``alg`` in header:

.. code-block:: python

    from joserfc import jwt, jwk
    from joserfc.jwk import OctKey

    header = {"alg": "HS256"}
    claims = {"iss": "https://authlib.org"}
    key = jwk.import_key("your-secret-key", "oct")
    text = jwt.encode(header, claims, key)

The returned value of ``text`` in above example is:

.. code-block:: none

    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
    eyJpc3MiOiJodHRwczovL2F1dGhsaWIub3JnIn0.
    Zm430u0j1wzf5Me5Zoj2h6dTt9IFsb7-G5mUW3BTWbo

Line breaks for display only.

Prevent sensitive data leaks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Before calling :meth:`encode` on your claims, it's a good practice to ensure
they do not contain sensitive information, such as credit card numbers.

You can use :meth:`check_sensitive_data` to detect whether sensitive data is
present in the claims:

.. code-block:: python

    from joserfc import jwt

    jwt.check_sensitive_data(claims)

Convert datetime
~~~~~~~~~~~~~~~~

:meth:`encode` will convert ``datetime`` to timestamp integer for ``iat``,
``exp``, and ``nbf``:

.. code-block:: python

    import datetime
    from joserfc import jwk, jwt

    now = datetime.datetime.now(datetime.UTC)
    claims = {
        "iss": "https://authlib.org",
        "iat": now,
        "exp": now + datetime.timedelta(minutes=5),
    }
    header = {"alg": "HS256"}
    key = jwk.import_key("your-secret-key", "oct")
    text = jwt.encode(header, claims, key)


Decode token
------------

:meth:`decode` is the method to translate a JSON Web Token string
into a token object which contains ``.header`` and ``.claims`` properties:

.. code-block:: python

    # reuse the text and key in above example
    token = jwt.decode(text, key)
    # token.header = {'alg': 'HS256', 'typ': 'JWT'}
    # token.claims = {"iss": "https://authlib.org"}

.. _claims:

Validate claims
---------------

The ``jwt.decode`` method will only verify if the payload is a JSON
base64 string.

You can define claims requests :class:`JWTClaimsRegistry` for validating the
decoded claims. The ``JWTClaimsRegistry`` accepts each claim as an
`Individual Claims Requests <http://openid.net/specs/openid-connect-core-1_0.html#IndividualClaimsRequests>`_
JSON object.

.. code-block:: python

    from joserfc.errors import ClaimError
    from joserfc.jwt import JWTClaimsRegistry

    claims_requests = JWTClaimsRegistry(
        iss={"essential": True, "value": "https://authlib.org"},
    )

    # usually you will use the claims registry after ``.decode``
    try:
        claims_requests.validate(token.claims)
    except ClaimError as error:
        print(error.claim, error.error, error.description)

The Individual Claims Requests JSON object contains:

``essential``
  OPTIONAL. Indicates whether the Claim being requested is an Essential Claim.
  If the value is true, this indicates that the Claim is an Essential Claim.

``value``
  OPTIONAL. Requests that the Claim be returned with a particular value.

``values``
  OPTIONAL. Requests that the Claim be returned with one of a set of values,
  with the values appearing in order of preference.

And we added one more field:

``allow_blank``
  OPTIONAL. Allow essential claims to be an empty string.

Missing essential claims
~~~~~~~~~~~~~~~~~~~~~~~~

When a claim is declared as ``essential``:

.. code-block:: python

    claims_requests = JWTClaimsRegistry(aud={"essential": True})

    # this will raise MissingClaimError, "aud" is missing
    claims = {"iss": "https://authlib.org"}
    claims_requests.validate(claims)

    # this will raise MissingClaimError, because "aud" is empty
    claims = {"aud": ""}
    claims_requests.validate(claims)

Allow empty essential claims
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

An ``essential`` claim with ``allow_blank`` can be an empty value:

.. code-block:: python

    claims_requests = JWTClaimsRegistry(iss={"essential": True, "allow_blank": True})

    # this will NOT raise MissingClaimError
    claims = {"iss": ""}
    claims_requests.validate(claims)

Invalid claims values
~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

    claims = {"iss": "https://authlib.org"}
    claims_requests = JWTClaimsRegistry(iss={"value": "https://jose.authlib.org"})

    claims_requests.validate(claims)  # this will raise InvalidClaimError

Default validators
~~~~~~~~~~~~~~~~~~

The ``JWTClaimsRegistry`` has built-in validators for timing related fields:

- ``exp``: expiration time
- ``nbf``: not before
- ``iat``: issued at

.. code-block:: python

    claims = {"iss": "https://authlib.org", "exp": 1765256501}
    claims_requests = JWTClaimsRegistry()
    claims_requests.validate(claims)  # this will raise ExpiredTokenError

List validation
~~~~~~~~~~~~~~~

When validating claims that contain lists, the registry checks if **any** of the
required values are present in the claim's list. This behavior is designed for
flexible authorization checks where matching any of the required permissions grants
access. For single values, it checks for an exact match.

This is particularly useful for validating role based or permission based claims. For
example:

.. code-block:: python

    # Claim containing a list of permissions
    claims = {"permissions": ["users:read", "users:write", "users:admin"]}

    # Passes since "users:write" is present in the list
    claims_requests = JWTClaimsRegistry(
        permissions={"values": ["users:write", "system:admin"]}
    )
    claims_requests.validate(claims)

    # Raises InvalidClaimError since none of the required values are present
    claims_requests = JWTClaimsRegistry(
        permissions={"values": ["system:admin"]}
    )
    claims_requests.validate(claims)

You can also validate against a single required value:

.. code-block:: python

    # Claim containing a list of permissions
    claims = {"permissions": ["users:read", "users:write", "users:admin"]}

    # Passes since "users:read" is present in the list
    claims_requests = JWTClaimsRegistry(
        permissions={"value": "users:read"}
    )
    claims_requests.validate(claims)

Custom validation
-----------------

When it's not possible to validate a claim using ``ClaimsOption``,
you can define a custom validation method named ``validate_{name}``.
For example, if the claims must include a ``source`` field, and the
value of ``source`` must be an HTTPS URL, you can implement a custom
method to enforce this requirement.

.. code-block:: python

    from joserfc.jwt import JWTClaimsRegistry
    from joserfc.errors import InvalidClaimError

    class MyClaimsRegistry(JWTClaimsRegistry):
        def validate_source(self, value):
            if not value.startswith('https://'):
                raise InvalidClaimError('source')

Then, you can validate the claims with:

.. code-block:: python

    claims_requests = MyClaimsRegistry(source={"essential": True})

JWS & JWE
---------

JWT is built on top of JWS and JWE, all of the above examples are in JWS. By default
``jwt.encode`` and ``jwt.decode`` work for **JWS**. To use **JWE**, you need to specify
a ``registry`` parameter with ``JWERegistry``. Here is an example of JWE:

.. code-block:: python

    from joserfc import jwt, jwe
    from joserfc.jwk import OctKey

    header = {"alg": "A128KW", "enc": "A128GCM"}
    claims = {"iss": "https://authlib.org"}
    key = OctKey.generate_key(128)  # the algorithm requires key of 128 bit size
    registry = jwe.JWERegistry()  # YOU MUST USE A JWERegistry
    jwt.encode(header, claims, key, registry=registry)

The JWE formatted result contains 5 parts, while JWS only contains 3 parts,
a JWE example would be something like this (line breaks for display only):

.. code-block:: none

    eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4R0NNIiwidHlwIjoiSldUIn0.
    F3plSTFE5GPJNs_qGsmoVx4o402URh5G.
    57P7XX6C3hJbk-Nl.
    dpgaZFi3uI1RiOqI3bmYY3_opkljIwcByf_j6fM.
    uv1BZZy5F-ci54BS11EYGg

Another difference is the key used for ``encode`` and ``decode``.

For :ref:`jws`, a private key is used for ``encode``, and a public key is used for
``decode``. The ``encode`` method will use a private key to sign, and the ``decode``
method will use a public key to verify.

For :ref:`jwe`, it is the contrary, a public key is used for ``encode``, and a private
key is used for ``decode``. The ``encode`` method  will use a public key to encrypt,
and the ``decode`` method will use a private key to decrypt.

The key parameter
-----------------

In the above example, we're using :ref:`OctKey` only for simplicity. There are other
types of keys in :ref:`jwk`.

Key types
~~~~~~~~~

Each algorithm (``alg`` in header) requires a certain type of key. For example:

- ``HS256`` requires ``OctKey``
- ``RS256`` requires ``RSAKey``
- ``ES256`` requires ``ECKey`` or ``OKPKey``

You can find the correct key type for each algorithm at:

- :ref:`JSON Web Signature Algorithms <jws_algorithms>`
- :ref:`JSON Web Encryption Algorithms <jwe_algorithms>`

Here is an example of a JWT with "alg" of ``RS256`` in JWS type:

.. code-block:: python

    from joserfc import jwt
    from joserfc.jwk import RSAKey

    header = {"alg": "RS256"}
    claims = {"iss": "https://authlib.org"}
    with open("your-private-rsa-key.pem") as f:
        key = RSAKey.import_key(f.read())

    # "RS256" is a recommended algorithm, no need to pass a custom ``registry``
    text = jwt.encode(header, claims, key)

    # ``.encode`` for JWS type use a public key, if using a private key,
    # it will automatically extract the public key from private key
    jwt.decode(text, key)

In production, ``jwt.encode`` is usually used by the *client* side, a client
normally does not have the access to private keys. The server provider would
usually expose the public keys in JWK Set.

Use key set
~~~~~~~~~~~

You can also pass a JWK Set to the ``key`` parameter of :meth:`encode` and
:meth:`decode` methods.

.. code-block:: python

    import json
    from joserfc.jwk import KeySet
    from joserfc import jwt

    with open("your-private-jwks.json") as f:
        data = json.load(f)
        key_set = KeySet.import_key_set(data)

    header = {"alg": "RS256", "kid": "1"}
    claims = {"iss": "https://authlib.org"}
    jwt.encode(header, claims, key_set)

The methods will find the correct key according to the ``kid`` you specified.
If there is no ``kid`` in header, it will pick one randomly and add the ``kid``
of the key into header.

A client would usually get the public key set from a public URL, normally the
``decode`` code would be something like:

.. code-block:: python

    import requests
    from joserfc import jwt
    from joserfc.jwt import Token
    from joserfc.jwk import KeySet

    resp = requests.get("https://example-site/jwks.json")
    key_set = KeySet.import_key_set(resp.json())

    def parse_token(token_string: str) -> Token:
        return jwt.decode(token_string, key_set)

Callable key
~~~~~~~~~~~~

It is also possible to assign a callable function as the ``key``:

.. code-block:: python

    import json
    from joserfc.jwk import KeySet
    from joserfc.jws import CompactSignature

    def load_key(obj: CompactSignature) -> KeySet:
        headers = obj.headers()
        alg = headers["alg"]
        key_path = f"my-{alg}-keys.json"
        with open(key_path) as f:
            data = json.load(f)
            return KeySet.import_key_set(data)

    # jwt.encode(header, claims, load_key)

Embedded JWK
~~~~~~~~~~~~

The key may be embedded directly in the token's header. For example,
the decoded header might look like this:

.. code-block:: json

    {
      "jwk": {
        "crv": "P-256",
        "x": "UM9g5nKnZXYovWAlM76cLz9vTozRj__CHU_dOl-gOoE",
        "y": "ds8aeQw1l2cDCA7bCkONvwDKpXAbtXjvqCleYH8Ws_U",
        "kty": "EC"
      },
      "alg": "ES256"
    }

In such cases, you don't need to supply a separate key manually. Instead,
as shown above, you can use a callable key function to dynamically
resolve the embedded JWK value.

.. code-block:: python

    from joserfc import jwk

    def embedded_jwk(obj: jwk.GuestProtocol) -> jwk.Key:
        headers = obj.headers()
        return jwk.import_key(headers["jwk"])

    # jwt.decode(value, embedded_jwk)

Embedded JWK Set URL
~~~~~~~~~~~~~~~~~~~~

As shown above, the key may also be provided as a JWK Set URL
within the token header, for example:

.. code-block:: json

    {
      "jku": "https://example-site/jwks.json",
      "alg": "ES256"
    }

In this case, you can use a callable key function to import the
JWKs:

.. code-block:: python

    import requests
    from joserfc.jwk import GuestProtocol, Key, KeySet

    def fetch_jwk_set(obj: GuestProtocol) -> Key:
        headers = obj.headers()
        resp = requests.get(headers["jku"])
        return KeySet.import_key_set(resp.json())

    jwt.decode(value, fetch_jwk_set)

.. hint::

    Use a cache method to improve the performance.

Algorithms & Registry
---------------------

The :meth:`encode` and :meth:`decode` accept an ``algorithms`` parameter for
specifying the allowed algorithms. By default, it only allows you to use the
**recommended** algorithms.

You can find out the recommended algorithms at:

- :ref:`JSON Web Signature Algorithms <jws_algorithms>`
- :ref:`JSON Web Encryption Algorithms <jwe_algorithms>`

For instance, ``HS384`` is not a recommended algorithm, and you want to use
this algorithm:

.. code-block:: python

    >>> from joserfc import jwt, jwk
    >>> header = {"alg": "HS384"}
    >>> claims = {"iss": "https://authlib.org"}
    >>> key = jwk.OctKey.import_key("your-secret-key")
    >>> jwt.encode(header, claims, key, algorithms=["HS384"])

If not specifying the ``algorithms`` parameter, the ``encode`` method will
raise an error.

JSON Encoder and Decoder
------------------------

.. versionadded:: 1.1.0

    The parameters ``encoder_cls`` for ``jwt.encode`` and ``decoder_cls`` for ``jwt.decode``
    were introduced in version 1.1.0.

When using ``jwt.encode`` to encode claims that contain data types that ``json``
module does not natively support, such as ``UUID`` and ``datetime``, an error will
be raised.

.. code-block:: python

    >>> import uuid
    >>> from joserfc import jwt, jwk
    >>>
    >>> key = jwk.OctKey.import_key("your-secret-key")
    >>> claims = {"sub": uuid.uuid4()}
    >>> jwt.encode({"alg": "HS256"}, claims, key)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File ".../joserfc/jwt.py", line 66, in encode
        payload = convert_claims(claims, encoder_cls)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File ".../joserfc/rfc7519/claims.py", line 36, in convert_claims
        content = json.dumps(claims, ensure_ascii=False, separators=(",", ":"), cls=encoder_cls)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File ".../lib/python3.12/json/__init__.py", line 238, in dumps
        **kw).encode(obj)
              ^^^^^^^^^^^
      File ".../lib/python3.12/json/encoder.py", line 200, in encode
        chunks = self.iterencode(o, _one_shot=True)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File ".../lib/python3.12/json/encoder.py", line 258, in iterencode
        return _iterencode(o, 0)
               ^^^^^^^^^^^^^^^^^
      File ".../lib/python3.12/json/encoder.py", line 180, in default
        raise TypeError(f'Object of type {o.__class__.__name__} '
    TypeError: Object of type UUID is not JSON serializable

To resolve this issue, you can pass a custom ``JSONEncoder`` using the ``encoder_cls`` parameter.

.. code-block:: python

    import uuid
    import json
    from joserfc import jwt, jwk

    class MyEncoder(json.JSONEncoder):
        def default(self, o):
            if isinstance(o, uuid.UUID):
                return str(o)
            return super().default(o)

    key = jwk.OctKey.import_key("your-secret-key")
    claims = {"sub": uuid.uuid4()}
    jwt.encode({"alg": "HS256"}, claims, key, encoder_cls=MyEncoder)

Additionally, ``jwt.decode`` accepts a ``decoder_cls`` parameter. If you need to convert
the decoded claims into the appropriate data types, you can provide a custom decoder class.