DEV Community

kingfujing
kingfujing

Posted on Originally published at devtoolshub.cloud

How to Decode a JWT Without a Library (JavaScript, Python, cURL)

Originally published on DevToolsHub โ€” free, privacy-first online tools for developers.

A JSON Web Token looks like encrypted gibberish, but it is not encrypted at
all โ€” it is three chunks of base64url-encoded JSON glued
together with dots. That means you can decode and read any JWT with the
tools you already have: atob() in the browser,
base64 in Python, or a one-liner in your terminal. No
jsonwebtoken, no PyJWT, no npm install. This is
exactly what you want when you are debugging an auth flow: which claims did
the server actually issue? When does this token expire? Is my user ID even
in there?

      In this guide you will learn the token structure, the one encoding quirk
      that breaks naive decoding attempts (base64url padding), working code for
      JavaScript, Python, and the shell, how to read the standard claims, and โ€”
      critically โ€” why **decoding is not verifying**, and what that
      distinction means for your code.
Enter fullscreen mode Exit fullscreen mode

๐Ÿ’ก Quick Try Paste a token into our free

JWT Decoder

to see the decoded header and payload instantly โ€” it runs entirely in your
browser and never sends your token anywhere. Need plain base64 work too?
The

Base64 Encoder / Decoder

handles standard and URL-safe variants.

The Three-Part Structure of a JWT

      Every JWT is three base64url segments joined by dots:
      `header.payload.signature`. Only the first two are JSON โ€” the
      signature is raw binary that happens to be base64url-encoded:
Enter fullscreen mode Exit fullscreen mode
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NSIsIm5hbWUiOiJBZGEiLCJpYXQiOjE3NjQyODgwMDB9signature

Decoded:
  part 1 (header)       <- signing algorithm
  part 2 (payload) {"sub":"12345","name":"Ada","iat":1764288000}  <- the claims
  part 3 (signature) raw HMAC bytes, not JSON
Enter fullscreen mode Exit fullscreen mode
      The header tells you the algorithm (`alg`) and usually the token
      type (`typ`). The payload โ€” called the "claims set" โ€”
      carries the actual data: user identity, scopes, issuance time, expiry. The
      signature proves the token was issued by whoever holds the signing key and
      that neither of the first two parts has been modified since. Because the
      first two parts are plain encoded JSON, anyone who receives the token can
      read everything in them. Never put secrets โ€” passwords, API keys, PANs โ€”
      inside a JWT payload.
Enter fullscreen mode Exit fullscreen mode

base64url vs Standard base64: The Padding Problem

      JWTs use **base64url** (RFC 4648 ยง5), a URL-safe variant of
      standard base64 with two differences: `+` becomes `-`
      , `/` becomes `_`, and โ€” the part that bites
      everyone โ€” **the `=` padding characters are stripped**.
      Standard decoders expect input whose length is a multiple of 4, so a
      segment straight out of a JWT will often fail or silently truncate:
Enter fullscreen mode Exit fullscreen mode
Standard base64:  "Hello" -> SGVsbG8=
base64url:        "Hello" -> SGVsbG8      (padding = removed)
URL-safe:         + becomes -, / becomes _

Segment lengths from a real token:
  eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9  (36 chars -> needs 0 padding)
  eyJzdWIiOiIxMjM0NSJ9                  (20 chars -> needs 0 padding)
  eyJzdWIiOiIxMjM0                      (18 chars -> needs 2 ==)
Enter fullscreen mode Exit fullscreen mode
      The fix is always the same: translate the URL-safe characters back to the
      standard alphabet, then re-add the stripped padding before decoding. Every
      recipe below does exactly this. JavaScript rounds the length up to a
      multiple of 4 with `padEnd`; Python lets
      `urlsafe_b64decode` do it with explicit `=`
      characters appended.
Enter fullscreen mode Exit fullscreen mode

Decode a JWT in JavaScript

      In the browser, `atob()` decodes standard base64 into a binary
      string. Wrap it with the two-step base64url normalization and parse the
      result as JSON:
Enter fullscreen mode Exit fullscreen mode
function decodeJwtPart(part) {
  // 1. base64url -> standard base64 alphabet
  const b64 = part.replace(/-/g, "+").replace(/_/g, "/");
  // 2. restore the stripped '=' padding
  const padded = b64.padEnd(b64.length + ((4 - (b64.length % 4)) % 4), "=");
  // 3. decode and parse
  return JSON.parse(atob(padded));
}

function decodeJwt(token) {
  const [header, payload, signature] = token.split(".");
  return {
    header: decodeJwtPart(header),
    payload: decodeJwtPart(payload),
    signature, // keep raw; not JSON
  };
}

const decoded = decodeJwt("eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.abc");
console.log(decoded.payload);   //
Enter fullscreen mode Exit fullscreen mode
      In Node.js 8+, you can skip the padding dance entirely because
      `Buffer.from(str, "base64url")` accepts unpadded
      base64url directly: `JSON.parse(Buffer.from(part, "base64url").toString("utf8"))`.
      In the browser `atob()` is your only built-in option, so keep
      the helper. One more gotcha: `atob()` throws an
      `InvalidCharacterError` on input with wrong padding, which is
      precisely why step 2 exists.
Enter fullscreen mode Exit fullscreen mode

Decode a JWT in Python

      Python's `base64.urlsafe_b64decode()` already handles the
      character translation (`-` to `+`, `_` to
      `/`) โ€” the only thing it will not do is invent missing padding.
      Add it yourself:
Enter fullscreen mode Exit fullscreen mode
import base64
import json

def decode_jwt(token: str) -> dict:
    header_b64, payload_b64, signature_b64 = token.split(".")
    def part(seg: str) -> dict:
        # urlsafe_b64decode needs padding to a multiple of 4
        padded = seg + "=" * (-len(seg) % 4)
        return json.loads(base64.urlsafe_b64decode(padded))
    return {
        "header": part(header_b64),
        "payload": part(payload_b64),
    }

token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSIsIm5hbWUiOiJBZGEifQ.sig"
print(decode_jwt(token)["payload"])
#
Enter fullscreen mode Exit fullscreen mode
      The expression `"=" * (-len(seg) % 4)` is the idiomatic
      Python padding trick: `-len(seg) % 4` is 0 when the length is
      already a multiple of 4, otherwise it is the exact number of `=`
      characters needed. Note that segments must be `str`, not
      `bytes`, for this particular call โ€” if your token came from a
      byte source, decode it to text first.
Enter fullscreen mode Exit fullscreen mode

Decode a JWT in the Terminal

      For a quick inspection without touching a REPL, `tr` translates
      the URL-safe alphabet and `base64 -d` decodes. GNU coreutils
      `base64` tolerates missing padding with `-d` on most
      distros; macOS users should add `python3` for the payload:
Enter fullscreen mode Exit fullscreen mode
TOKEN="eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NSJ9.abc"

# Header (part 1)
echo "$TOKEN" | cut -d. -f1 | tr '_-' '/+' | base64 -d 2>/dev/null; echo
#

# Payload (part 2)
echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null; echo
#

# Portable version that adds padding explicitly (works on macOS):
echo "$TOKEN" | cut -d. -f2 | tr '_-' '/+' | python3 -c \\
  "import sys,base64,json; s=sys.stdin.read().strip(); \\
   print(json.dumps(json.loads(base64.urlsafe_b64decode(s + '=' * (-len(s) % 4)))))"
Enter fullscreen mode Exit fullscreen mode
      If `base64 -d` errors with *invalid input* on macOS, it
      is the missing padding โ€” that is what the `python3` fallback
      solves. Some systems also ship `openssl base64 -d -A`, which is
      strict about padding and needs the `=` characters appended by
      hand. When you just want the answer with zero fuss, paste the token into
      the
      [
        JWT Decoder
      ](https://devtoolshub.cloud/tools/jwt-decoder)
      , which decodes both JSON parts and pretty-prints the claims.
Enter fullscreen mode Exit fullscreen mode

Reading the Standard Claims: exp, iat, iss, sub

      The JWT spec (RFC 7519) defines a small set of registered claims that
      almost every auth system uses. Once decoded, you can answer most debugging
      questions from five fields:
Enter fullscreen mode Exit fullscreen mode
{
  "sub": "user_98123",      // subject: the user or entity this token is about
  "iss": "https://auth.example.com",  // issuer: who created and signed it
  "aud": "api.example.com", // audience: which service should accept it
  "iat": 1764288000,        // issued at: Unix seconds
  "exp": 1764291600,        // expiration: Unix seconds
  "scope": "read:items"     // custom claim: permissions
}
Enter fullscreen mode Exit fullscreen mode
      `exp` and `iat` are **Unix timestamps in
      seconds** โ€” a quick expiry check in JavaScript is
      `payload.exp * 1000 > Date.now()`, and in Python
      `payload["exp"] > time.time()`. If a token is being
      rejected, compare `iss` against what your server expects and
      check whether `aud` matches the consuming service โ€” issuer and
      audience mismatches are the second most common rejection cause after
      expiry. Clock skew between machines can also flip a valid token to expired
      for a few seconds, which is why libraries accept a small `leeway`.
Enter fullscreen mode Exit fullscreen mode

Decoding Is Not Verifying (and Why It Matters)

      Everything in this guide reads the token. None of it **proves**
      the token is authentic. The signature is an HMAC or RSA/ECDSA computation
      over the first two parts using a secret or public key, and until you
      recompute and compare it, an attacker could have swapped the payload,
      `alg` header, or `exp` claim freely. The classic
      exploit pattern: take a valid token, change the payload to say
      `"}`, and hand it to a server that decodes
      without verifying โ€” it will happily trust the forged claims.
Enter fullscreen mode Exit fullscreen mode
// Decoding (reading): safe anywhere, proves nothing
const payload = decodeJwt(token).payload;

// Verifying (trusting): requires the key and a constant-time comparison
// - HMAC (HS256): server secret, e.g. with the jsonwebtoken library
// - RS256/ES256: public key from the issuer's JWKS endpoint
// Only enforce authorization AFTER verification succeeds.
Enter fullscreen mode Exit fullscreen mode
      The rule is simple: **decode for debugging, verify for
      authorization**. Manual decoding is perfect for development,
      logging, and inspecting tokens you already hold. But server-side request
      handling must verify the signature with the correct key and algorithm
      (using a vetted library โ€” hand-rolling signature comparison invites timing
      attacks), check `exp`, and validate `iss` and
      `aud` before trusting a single claim.
Enter fullscreen mode Exit fullscreen mode

Common Mistakes & How to Avoid Them

      -
        **Using standard base64 decoding on JWT segments.** The
        payload fails or returns mojibake because JWTs strip the `=`
        padding and swap `+/` for `-_`. Normalize the
        alphabet and restore padding first โ€” every recipe above shows the two
        steps.


      -
        **Treating decoding as authentication.** A decoded token is
        not a trusted token. Authorization decisions must wait until the
        signature, `exp`, `iss`, and `aud` have
        been verified server-side with the proper key.


      -
        **Trying to JSON.parse the signature.** The third segment is
        raw binary, not JSON โ€” parsing it throws. Only the first two parts are
        JSON; pass the signature through unchanged.


      -
        **Putting sensitive data in the payload.** Anyone with the
        token can read it โ€” decoding requires zero secrets. Store an opaque user
        ID in `sub` and keep credentials out of JWTs entirely.


      -
        **Comparing exp in the wrong unit.** The `exp`
        claim is in **seconds**, while JavaScript's
        `Date.now()` is milliseconds. Multiply by 1000 before
        comparing, or your valid tokens will always look expired.
Enter fullscreen mode Exit fullscreen mode

Frequently Asked Questions

Does decoding a JWT verify its signature?

No. Decoding just reverses the base64url encoding and shows you the
JSON inside. Verification recomputes the signature over the header
and payload using the signing key and compares it to the third
segment. Anyone can decode any token; only a holder of the key can
produce a token whose signature checks out. Decode for debugging,
verify before enforcing authorization.

Is it safe to paste my JWT into an online decoder?

It depends on where decoding happens. Our
JWT Decoder
runs entirely in your browser: the token never leaves your machine,
which you can confirm in the network tab. As a general habit, assume
tokens pasted into any server-side tool are compromised and revoke
or let them expire. For production secrets, decode locally with the
snippets in this article instead.

Why is base64 decode failing on JWT parts?

Almost always padding. JWTs strip the trailing = characters, so
segment length is rarely a multiple of 4, and standard decoders
reject or truncate such input. Translate - to + and _ to /, append
enough = to reach a multiple of 4 (in JS: padEnd with (4 - length
modulo 4) modulo 4; in Python: seg + "=" times
(-len(seg) modulo 4)), then decode.

Where is the password stored in a JWT?

Nowhere, and it should stay that way. A JWT payload is base64url
encoded, not encrypted, so anyone who holds the token can read every
claim. Passwords, keys, and card numbers must never go into a JWT.
If you need confidentiality, use JWE (encrypted JWTs) or keep
sensitive data server-side and reference it by an opaque ID in the
sub claim.

How do I check if a JWT is expired?

Decode the payload and compare the exp claim to the current time.
exp is Unix seconds: in JavaScript, payload.exp * 1000 > Date.now()
means still valid; in Python, payload.get("exp", 0) >
time.time(). Add a small leeway (30 to 60 seconds) to tolerate clock
skew. A token without an exp claim never expires by itself, which
most systems treat as a red flag rather than a feature.

        **Related Tools:**
        [JWT Decoder](https://devtoolshub.cloud/tools/jwt-decoder)

        [Base64 Encoder / Decoder](https://devtoolshub.cloud/tools/base64)

        [JSON Formatter](https://devtoolshub.cloud/tools/json-formatter)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)