summaryrefslogtreecommitdiff
path: root/docs/usage.rst
blob: 9a673c3e91ce6dcb74fee7123a8800638857af1f (plain)
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
Usage Examples
==============

Encoding & Decoding Tokens with HS256
-------------------------------------

.. code-block:: pycon

    >>> import jwt
    >>> key = "secret"
    >>> encoded = jwt.encode({"some": "payload"}, key, algorithm="HS256")
    >>> print(encoded)
    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg
    >>> jwt.decode(encoded, key, algorithms="HS256")
    {'some': 'payload'}

Encoding & Decoding Tokens with RS256 (RSA)
-------------------------------------------

RSA encoding and decoding require the ``cryptography`` module. See :ref:`installation_cryptography`.

.. code-block:: pycon

    >>> import jwt
    >>> private_key = b"-----BEGIN PRIVATE KEY-----\nMIGEAgEAMBAGByqGSM49AgEGBS..."
    >>> public_key = b"-----BEGIN PUBLIC KEY-----\nMHYwEAYHKoZIzj0CAQYFK4EEAC..."
    >>> encoded = jwt.encode({"some": "payload"}, private_key, algorithm="RS256")
    >>> print(encoded)
    eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg
    >>> decoded = jwt.decode(encoded, public_key, algorithms=["RS256"])
    {'some': 'payload'}

If your private key needs a passphrase, you need to pass in a ``PrivateKey`` object from ``cryptography``.

.. code-block:: python

    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend

    pem_bytes = b"-----BEGIN PRIVATE KEY-----\nMIGEAgEAMBAGByqGSM49AgEGBS..."
    passphrase = b"your password"

    private_key = serialization.load_pem_private_key(
        pem_bytes, password=passphrase, backend=default_backend()
    )
    encoded = jwt.encode({"some": "payload"}, private_key, algorithm="RS256")

If you are repeatedly encoding with the same private key, reusing the same
``RSAPrivateKey`` also has performance benefits because it avoids the
CPU-intensive ``RSA_check_key`` primality test.

Specifying Additional Headers
-----------------------------

.. code-block:: pycon

    >>> jwt.encode(
    ...     {"some": "payload"},
    ...     "secret",
    ...     algorithm="HS256",
    ...     headers={"kid": "230498151c214b788dd97f22b85410a5"},
    ... )
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjIzMDQ5ODE1MWMyMTRiNzg4ZGQ5N2YyMmI4NTQxMGE1In0.eyJzb21lIjoicGF5bG9hZCJ9.DogbDGmMHgA_bU05TAB-R6geQ2nMU2BRM-LnYEtefwg'


Reading the Claimset without Validation
---------------------------------------

If you wish to read the claimset of a JWT without performing validation of the
signature or any of the registered claim names, you can set the
``verify_signature`` option to ``False``.

Note: It is generally ill-advised to use this functionality unless you
clearly understand what you are doing. Without digital signature information,
the integrity or authenticity of the claimset cannot be trusted.

.. code-block:: pycon

    >>> jwt.decode(encoded, options={"verify_signature": False})
    {'some': 'payload'}

Reading Headers without Validation
----------------------------------

Some APIs require you to read a JWT header without validation. For example,
in situations where the token issuer uses multiple keys and you have no
way of knowing in advance which one of the issuer's public keys or shared
secrets to use for validation, the issuer may include an identifier for the
key in the header.

.. code-block:: pycon

    >>> jwt.get_unverified_header(encoded)
    {'alg': 'RS256', 'typ': 'JWT', 'kid': 'key-id-12345...'}

Registered Claim Names
----------------------

The JWT specification defines some registered claim names and defines
how they should be used. PyJWT supports these registered claim names:

 - "exp" (Expiration Time) Claim
 - "nbf" (Not Before Time) Claim
 - "iss" (Issuer) Claim
 - "aud" (Audience) Claim
 - "iat" (Issued At) Claim

Expiration Time Claim (exp)
~~~~~~~~~~~~~~~~~~~~~~~~~~~

    The "exp" (expiration time) claim identifies the expiration time on
    or after which the JWT MUST NOT be accepted for processing.  The
    processing of the "exp" claim requires that the current date/time
    MUST be before the expiration date/time listed in the "exp" claim.
    Implementers MAY provide for some small leeway, usually no more than
    a few minutes, to account for clock skew.  Its value MUST be a number
    containing a NumericDate value.  Use of this claim is OPTIONAL.

You can pass the expiration time as a UTC UNIX timestamp (an int) or as a
datetime, which will be converted into an int. For example:

.. code-block:: python

    jwt.encode({"exp": 1371720939}, "secret")
    jwt.encode({"exp": datetime.now(tz=timezone.utc)}, "secret")

Expiration time is automatically verified in `jwt.decode()` and raises
`jwt.ExpiredSignatureError` if the expiration time is in the past:

.. code-block:: python

    try:
        jwt.decode("JWT_STRING", "secret", algorithms=["HS256"])
    except jwt.ExpiredSignatureError:
        # Signature has expired
        ...

Expiration time will be compared to the current UTC time (as given by
`timegm(datetime.now(tz=timezone.utc).utctimetuple())`), so be sure to use a UTC timestamp
or datetime in encoding.

You can turn off expiration time verification with the `verify_exp` parameter in the options argument.

PyJWT also supports the leeway part of the expiration time definition, which
means you can validate a expiration time which is in the past but not very far.
For example, if you have a JWT payload with a expiration time set to 30 seconds
after creation but you know that sometimes you will process it after 30 seconds,
you can set a leeway of 10 seconds in order to have some margin:

.. code-block:: python

    jwt_payload = jwt.encode(
        {"exp": datetime.datetime.now(tz=timezone.utc) + datetime.timedelta(seconds=30)},
        "secret",
    )

    time.sleep(32)

    # JWT payload is now expired
    # But with some leeway, it will still validate
    jwt.decode(jwt_payload, "secret", leeway=10, algorithms=["HS256"])

Instead of specifying the leeway as a number of seconds, a `datetime.timedelta`
instance can be used. The last line in the example above is equivalent to:

.. code-block:: python

    jwt.decode(
        jwt_payload, "secret", leeway=datetime.timedelta(seconds=10), algorithms=["HS256"]
    )

Not Before Time Claim (nbf)
~~~~~~~~~~~~~~~~~~~~~~~~~~~

    The "nbf" (not before) claim identifies the time before which the JWT
    MUST NOT be accepted for processing.  The processing of the "nbf"
    claim requires that the current date/time MUST be after or equal to
    the not-before date/time listed in the "nbf" claim.  Implementers MAY
    provide for some small leeway, usually no more than a few minutes, to
    account for clock skew.  Its value MUST be a number containing a
    NumericDate value.  Use of this claim is OPTIONAL.

The `nbf` claim works similarly to the `exp` claim above.

.. code-block:: python

    jwt.encode({"nbf": 1371720939}, "secret")
    jwt.encode({"nbf": datetime.now(tz=timezone.utc)}, "secret")

Issuer Claim (iss)
~~~~~~~~~~~~~~~~~~

    The "iss" (issuer) claim identifies the principal that issued the
    JWT.  The processing of this claim is generally application specific.
    The "iss" value is a case-sensitive string containing a StringOrURI
    value.  Use of this claim is OPTIONAL.

.. code-block:: python

    payload = {"some": "payload", "iss": "urn:foo"}

    token = jwt.encode(payload, "secret")
    decoded = jwt.decode(token, "secret", issuer="urn:foo", algorithms=["HS256"])

If the issuer claim is incorrect, `jwt.InvalidIssuerError` will be raised.

Audience Claim (aud)
~~~~~~~~~~~~~~~~~~~~

    The "aud" (audience) claim identifies the recipients that the JWT is
    intended for.  Each principal intended to process the JWT MUST
    identify itself with a value in the audience claim.  If the principal
    processing the claim does not identify itself with a value in the
    "aud" claim when this claim is present, then the JWT MUST be
    rejected.

In the general case, the "aud" value is an array of case-
sensitive strings, each containing a StringOrURI value.

.. code-block:: python

    payload = {"some": "payload", "aud": ["urn:foo", "urn:bar"]}

    token = jwt.encode(payload, "secret")
    decoded = jwt.decode(token, "secret", audience="urn:foo", algorithms=["HS256"])

In the special case when the JWT has one audience, the "aud" value MAY be
a single case-sensitive string containing a StringOrURI value.

.. code-block:: python

    payload = {"some": "payload", "aud": "urn:foo"}

    token = jwt.encode(payload, "secret")
    decoded = jwt.decode(token, "secret", audience="urn:foo", algorithms=["HS256"])

If multiple audiences are accepted, the ``audience`` parameter for
``jwt.decode`` can also be an iterable

.. code-block:: python

    payload = {"some": "payload", "aud": "urn:foo"}

    token = jwt.encode(payload, "secret")
    decoded = jwt.decode(
        token, "secret", audience=["urn:foo", "urn:bar"], algorithms=["HS256"]
    )

The interpretation of audience values is generally application specific.
Use of this claim is OPTIONAL.

If the audience claim is incorrect, `jwt.InvalidAudienceError` will be raised.

Issued At Claim (iat)
~~~~~~~~~~~~~~~~~~~~~

    The iat (issued at) claim identifies the time at which the JWT was issued.
    This claim can be used to determine the age of the JWT. Its value MUST be a
    number containing a NumericDate value. Use of this claim is OPTIONAL.

    If the `iat` claim is not a number, an `jwt.InvalidIssuedAtError` exception will be raised.

.. code-block:: python

    jwt.encode({"iat": 1371720939}, "secret")
    jwt.encode({"iat": datetime.now(tz=timezone.utc)}, "secret")

Requiring Presence of Claims
----------------------------

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.

.. code-block:: pycon

    >>> jwt.decode(encoded, options={"require": ["exp", "iss", "sub"]})
    {'exp': 1371720939, 'iss': 'urn:foo', 'sub': '25c37522-f148-4cbf-8ee6-c4a9718dd0af'}

Retrieve RSA signing keys from a JWKS endpoint
----------------------------------------------


.. code-block:: pycon

    >>> import jwt
    >>> from jwt import PyJWKClient
    >>> token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6Ik5FRTFRVVJCT1RNNE16STVSa0ZETlRZeE9UVTFNRGcyT0Rnd1EwVXpNVGsxUWpZeVJrUkZRdyJ9.eyJpc3MiOiJodHRwczovL2Rldi04N2V2eDlydS5hdXRoMC5jb20vIiwic3ViIjoiYVc0Q2NhNzl4UmVMV1V6MGFFMkg2a0QwTzNjWEJWdENAY2xpZW50cyIsImF1ZCI6Imh0dHBzOi8vZXhwZW5zZXMtYXBpIiwiaWF0IjoxNTcyMDA2OTU0LCJleHAiOjE1NzIwMDY5NjQsImF6cCI6ImFXNENjYTc5eFJlTFdVejBhRTJINmtEME8zY1hCVnRDIiwiZ3R5IjoiY2xpZW50LWNyZWRlbnRpYWxzIn0.PUxE7xn52aTCohGiWoSdMBZGiYAHwE5FYie0Y1qUT68IHSTXwXVd6hn02HTah6epvHHVKA2FqcFZ4GGv5VTHEvYpeggiiZMgbxFrmTEY0csL6VNkX1eaJGcuehwQCRBKRLL3zKmA5IKGy5GeUnIbpPHLHDxr-GXvgFzsdsyWlVQvPX2xjeaQ217r2PtxDeqjlf66UYl6oY6AqNS8DH3iryCvIfCcybRZkc_hdy-6ZMoKT6Piijvk_aXdm7-QQqKJFHLuEqrVSOuBqqiNfVrG27QzAPuPOxvfXTVLXL2jek5meH6n-VWgrBdoMFH93QEszEDowDAEhQPHVs0xj7SIzA"
    >>> kid = "NEE1QURBOTM4MzI5RkFDNTYxOTU1MDg2ODgwQ0UzMTk1QjYyRkRFQw"
    >>> url = "https://dev-87evx9ru.auth0.com/.well-known/jwks.json"
    >>> optional_custom_headers = {"User-agent": "custom-user-agent"}
    >>> jwks_client = PyJWKClient(url, headers=optional_custom_headers)
    >>> signing_key = jwks_client.get_signing_key_from_jwt(token)
    >>> data = jwt.decode(
    ...     token,
    ...     signing_key.key,
    ...     algorithms=["RS256"],
    ...     audience="https://expenses-api",
    ...     options={"verify_exp": False},
    ... )
    >>> print(data)
    {'iss': 'https://dev-87evx9ru.auth0.com/', 'sub': 'aW4Cca79xReLWUz0aE2H6kD0O3cXBVtC@clients', 'aud': 'https://expenses-api', 'iat': 1572006954, 'exp': 1572006964, 'azp': 'aW4Cca79xReLWUz0aE2H6kD0O3cXBVtC', 'gty': 'client-credentials'}

OIDC Login Flow
---------------

The following usage demonstrates an OIDC login flow using pyjwt. Further
reading about the OIDC spec is recommended for implementers.

In particular, this demonstrates validation of the ``at_hash`` claim.
This claim relies on data from outside of the the JWT for validation. Methods
are provided which support computation and validation of this claim, but it
is not built into pyjwt.

.. code-block:: python

    import base64
    import jwt
    import requests


    # Part 1: setup
    # get the OIDC config and JWKs to use

    # in OIDC, you must know your client_id (this is the OAuth 2.0 client_id)
    client_id = ...

    # example of fetching data from your OIDC server
    # see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig
    oidc_server = ...
    oidc_config = requests.get(
        f"https://{oidc_server}/.well-known/openid-configuration"
    ).json()
    signing_algos = oidc_config["id_token_signing_alg_values_supported"]

    # setup a PyJWKClient to get the appropriate signing key
    jwks_client = jwt.PyJWKClient(oidc_config["jwks_uri"])


    # Part 2: login / authorization
    # when a user completes an OIDC login flow, there will be a well-formed
    # response object to parse/handle

    # data from the login flow
    # see: https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
    token_response = ...
    id_token = token_response["id_token"]
    access_token = token_response["access_token"]


    # Part 3: decode and validate at_hash
    # after the login is complete, the id_token needs to be decoded
    # this is the stage at which an OIDC client must verify the at_hash

    # get signing_key from id_token
    signing_key = jwks_client.get_signing_key_from_jwt(id_token)

    # now, decode_complete to get payload + header
    data = jwt.decode_complete(
        id_token,
        key=signing_key.key,
        algorithms=signing_algos,
        audience=client_id,
    )
    payload, header = data["payload"], data["header"]

    # get the pyjwt algorithm object
    alg_obj = jwt.get_algorithm_by_name(header["alg"])

    # compute at_hash, then validate / assert
    digest = alg_obj.compute_hash_digest(access_token)
    at_hash = base64.urlsafe_b64encode(digest[: (len(digest) // 2)]).rstrip("=")
    assert at_hash == payload["at_hash"]