How to decode a JWT in Python (and what decoding does not prove)
How to decode a JWT in Python (and what decoding does not prove) Read any token with the stdlib or PyJWT, then see exactly where decoding stops and verifying starts. TL;DR The stdlib decode is a split, a padding line, base64.urlsafe_b64decode and json.loads . The padding line is what most snippets omit. To inspect a token, call jwt.decode_complete(token, options={"verify_signature": False}) . To…
To decode a JWT in Python, you first split the token on the dots, restore the "=" padding that base64url dropped, and then parse the result as JSON. The most common way to do this involves using the stdlib and PyJWT libraries.
After splitting the token, Python's base64.urlsafe_b64decode is used to decode the payload segment, which then gets parsed with json.loads. The padding line is an important step, as many snippets omit it but it is crucial for the decoding to work. The header contains information about the algorithm and the claims, while the payload holds the issuer, subject, audience, role, timestamps, and a unique token ID. The signature segment, which is a raw base64url string, is not parsed as JSON.
One thing to note is that adding the appropriate "=" padding to the payload segment before decoding can prevent padding errors. A sample script provided in the source demonstrates how to decode a token, handle errors, and verify the contents of the decoded token, including checking the expected issuer and the audience.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to