learn deep. ship safe.Practice testsFollow ByteMunSubscribe

mediumIdentityWeb security

Decode a JWT Payload

Decode the claims inside a JSON Web Token by hand, and learn why decoding is not verifying: anyone can read, or forge, an unsigned payload.

JavaScript or Python

A JWT has three Base64url-encoded parts separated by dots: header, payload and signature. Given a token, return its payload as an object. Base64url uses - and _ instead of + and / and drops the = padding, so you must restore both before decoding.

This only reads the token. It does not check the signature, so the result must never be trusted for authorisation; that is the point of the exercise.

Examples

Example 1

Input: token = header + "." + base64url('{"sub":"42","role":"user"}') + ".sig"
Output: {"sub": "42", "role": "user"}
Why: The middle part decodes to the claims

Example 2

Input: a token whose payload is {"admin": true}
Output: {"admin": true}
Why: Anyone can write this payload; only a verified signature makes it trustworthy

Constraints

  • The token has exactly three dot-separated parts
  • The payload is valid UTF-8 JSON

Hints

Hint 1

Take the part between the first and second dots.

Hint 2

Convert Base64url to Base64 (- to +, _ to /), add = until the length is a multiple of 4, then decode and parse the JSON.

Solution

Show the solution (try it yourself first)

Split on dots, take the payload part, restore standard Base64 padding (and characters, in JavaScript), decode the bytes as UTF-8 and parse the JSON.

import base64
import json

def jwt_payload(token):
    part = token.split(".")[1]
    part += "=" * (-len(part) % 4)
    return json.loads(base64.urlsafe_b64decode(part).decode("utf-8"))

Complexity

O(n) in the token length. The security lesson is the real answer: a JWT's claims are readable by anyone, so never put secrets in them, and an API must verify the signature with a pinned algorithm and key and check exp, iss and aud before trusting any claim. Code that decodes and trusts, or accepts alg: none, lets attackers simply write {"admin": true}.

Found a mistake in this problem, its tests or the solution?

Written by Published Tests checked by Deepak
Case 1Input: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsInJvbGUiOiJ1c2VyIn0.c2lnbmF0dXJl"Expected: {"sub":"42","role":"user"}
Case 2Input: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6dHJ1ZX0.c2lnbmF0dXJl"Expected: {"admin":true}

Run checks these 2 samples. Submit checks all 6 tests, including hidden ones.

  1. IP Address in CIDR RangeNetwork security · Web security
    medium
  2. Password Policy CheckerPasswords · Identity
    easy
  3. Maximum Subarray SumArrays · Dynamic programming
    medium
  4. Longest Substring Without RepeatsStrings · Sliding window · Hash map
    medium