Skip to main content

Decode vs Verify

In Create and Verify a JWT in Code, every program checked a token before it trusted a word of it. Most JWT libraries also have a second way to read a token, one that needs no key at all: decoding. The two calls look alike and hand back the same claims, yet only one of them proves anything. This tutorial shows the difference the way an attacker would: it takes a real token, changes the user's role from member to admin, and gives the forged copy to each library's decode and verify functions, in eight languages.

Decoding Reads a Token; Verifying Checks It​

A JWT is three pieces of base64url text joined by dots: a header, a payload and a signature. Decoding and verifying both start from those three pieces, then part ways.

Decoding only reads. It splits the token at the dots, turns the first two pieces back into JSON and gives you the claims. It needs no key, so anyone who holds a token can decode it: your own code, the person the token was issued to, or someone who copied it out of a log file. How to Decode a JWT in the Terminal does it with nothing but a terminal.

Verifying answers the question that matters: did the holder of the key write these exact claims? The library computes the signature again from the header, the payload and the key, and compares the result with the token's third piece. If they differ by a single character, it rejects the token. Only when they match does it check the claims themselves, such as the expiry, and hand them back.

Why Anyone Can Change the Claims​

The payload isn't encrypted. Base64url is a way to write bytes with letters and digits, not a lock, so anyone who holds a token can decode the payload, edit a claim, encode it again and put it back between the same header and signature. The result still looks like any other JWT: three pieces and two dots.

What nobody can do without the key is make a signature that fits the new claims. The signature was computed over the original header and payload, so once the payload changes, the old signature no longer matches it. Comparing the two is exactly what verifying does, and exactly what decoding skips. What Is a JWT? showed this by hand in a terminal. This tutorial shows that a library's decode function doesn't notice the change either.

RFC 8725, the JWT best-practice standard, puts the rule in one line in section 3.3: "All cryptographic operations used in the JWT MUST be validated and the entire JWT MUST be rejected if any of them fail to validate."

What Decoding Is For​

Reading a token without trusting it has a few honest uses, which is why most libraries offer a decode function:

  • Choosing a key. A token's header can name the key that signed it, in a kid field. A service that holds several keys reads the header first, looks that key up in its own list and then verifies with it. The header can be forged as easily as the payload, so use it only to pick among keys you already trust, and check the value before you look anything up with it: section 3.10 of RFC 8725 is titled "Do Not Trust Received Claims". The JOSE Header (coming soon) covers this in full.
  • Knowing when to sign in again. A browser or mobile app can read its own token's exp to refresh it before it runs out. The app isn't trusting the token for anything; the API still verifies every request.
  • Debugging. Decoding a token shows what a sign-in service actually put in it. Treat the token like a password while you do: anyone who has a copy can use it until it expires.

What a decoded claim must never do is decide who the user is or what they may do. That decision needs claims your code has verified.

Each Library's Decode Function​

LanguageLibraryRead the claims without the keyWhat its documentation says
Node.jsjosedecodeJwt(token)"Decodes the Claims Set of a JWT … without validating its JWS Signature (digital signature or MAC) or claim types and values."
PythonPyJWTjwt.decode(token, options={"verify_signature": False})"It is generally ill-advised to use this functionality unless you clearly understand what you are doing."
C#JsonWebTokenHandlerReadJsonWebToken(token)"The token is NOT validated and no security decisions should be made about the contents."
JavajjwtNone: you decode the payload yourself"If a JWS and signature verification fails … the JWT cannot be safely trusted and should be discarded."
Gogolang-jwtjwt.NewParser().ParseUnverified(token, claims)"WARNING: Don't use this method unless you know what you're doing."
PHPphp-jwtNone: you decode the payload with its helpersAbout reading a header this way: "This operation is vulnerable to attacks, as the JWT has not yet been verified."
RubyjwtJWT.decode(token, nil, false)The third argument is verify, "whether to verify the JWT signature."
Rustjsonwebtokendangerous::insecure_decode::<Claims>(token)"Decode a JWT with NO VALIDATION … DANGER: This performs zero validation on the JWT"

The names do some of the warning for you. Go calls its function ParseUnverified, and Rust keeps its function in a module named dangerous. jjwt goes further and has no such function at all: every way of parsing a signed token needs a key, and without one it stops with Cannot verify JWS signature: unable to locate signature verification key. php-jwt has no decode function either, so in Java and PHP the program decodes the payload piece itself, which Step 5 shows.

Decoding skips the expiry as well. Given a token that had expired an hour earlier, all eight ways of decoding returned its claims without an error, the two by hand included.

The Example​

The program plays three parts at once:

  • The sign-in service creates a genuine token for Zara: sub is user-42, name is Zara, role is member, and it expires in 15 minutes. It signs the token with the shared key, as in the last tutorial.
  • Anyone who holds that token, Zara included, makes a forged copy without the key. They keep the header and the signature, and write a payload of their own with role set to admin and exp set to 4102444800, which is 1 January 2100.
  • The orders API looks at both tokens twice: once by decoding them, as careless code does, and once by verifying them, as it should.

The program prints both tokens, then what decoding and verifying make of each one.

Prerequisites​

  • The tools for your language. Pick its tab and check them. These are the versions this tutorial was run with:

Node.js 26, which comes with npm:

Terminal
node --version
npm --version
Output
v26.13.1
12.2.3

Step 1: Create a Project and Add the JWT Library​

Each project lives in its own folder. Where a tab starts with mkdir decode-vs-verify and cd decode-vs-verify, those two commands create the folder and move into it. The other tools create the folder themselves. The commands are the same in every terminal, including PowerShell.

Terminal
mkdir decode-vs-verify
cd decode-vs-verify
npm init -y
npm pkg set type=module
npm install jose
  • npm init -y creates a package.json, the file that describes a Node.js project, without asking any questions.
  • npm pkg set type=module makes the project use ES modules, so the code can load jose with import. npm 12 writes "type": "commonjs" into a new package.json, as the output shows.
  • npm install jose downloads jose into a node_modules folder and adds it to package.json.
Output
Wrote to /Users/Shared/you/decode-vs-verify/package.json:
{
"name": "decode-vs-verify",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"type": "commonjs"
}
added 1 package, and audited 2 packages in 893ms
1 package is looking for funding
run `npm fund` for details
found 0 vulnerabilities

package.json now says the project is a module and depends on jose:

package.json
{
"name": "decode-vs-verify",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"type": "module",
"dependencies": {
"jose": "^6.2.18"
}
}

Step 2: Give the Program a Secret​

Both services need the same secret: 32 random bytes, the size RFC 7518 requires for HS256. The program reads it from an environment variable named JWT_SECRET, so the secret never sits in the code. How to Generate a Secret Key for HS256 JWTs in the Terminal explains the command, and How to Set an Environment Variable in the Terminal explains the variable.

Terminal
export JWT_SECRET=$(openssl rand -base64 32)
echo ${#JWT_SECRET}
Output
44

A zsh terminal where export JWT_SECRET stores the output of openssl rand -base64 32 and echo with a hash sign prints its length, 44 characters.

JWT_SECRET now holds the 32 bytes as 44 characters of base64 text, and the program decodes that text back into the 32 bytes it uses as the key. The length check confirms the variable is set without printing the secret on your screen. The variable lasts until you close this terminal, so run the program from the same window.

Step 3: Write the Code That Creates a Genuine Token​

Create the program's file: main.js, main.py, Program.cs, src/main/java/com/example/Main.java, main.go, main.php, main.rb or src/main.rs, depending on your language. Most editors create the folders in the path for you. In Python, C# and Rust, replace what the template put in the file. The code goes in over the next five steps, and the complete file shows it all together.

The first piece is the sign-in service from the last tutorial with one more claim, role. Applications use a claim like this to decide what someone may do, which is exactly what makes it worth forging. The function takes the key, a user ID, a name and a role, and returns a signed token with sub, name, role and exp, 15 minutes from now.

main.js
import { SignJWT, decodeJwt, jwtVerify, errors } from 'jose';

// The sign-in service's job: sign a token with the user's name and role.
async function createToken(key, userId, name, role) {
return new SignJWT({ name, role })
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setSubject(userId)
.setExpirationTime('15m')
.sign(key);
}
  • new SignJWT({ name, role }) puts your own claims in the payload, and .setSubject() and .setExpirationTime('15m') add sub and exp.
  • The import line also brings in decodeJwt, the decode function Step 5 uses.

Step 4: Forge a Copy Without the Key​

Now the program does what anyone who holds Zara's token could do. It splits the token at its dots, keeps the first and third pieces, the header and the signature, and puts a payload of its own between them. The new payload is plain JSON text: Zara's sub and name, the role admin, and exp set to 4102444800, the first second of the year 2100. Base64url-encoding that text makes it look like any other payload. Nothing in this step uses the key.

main.js
// What anyone can do without the key: swap in claims of their own.
function forgeToken(token) {
const parts = token.split('.');
const claims = '{"sub":"user-42","name":"Zara","role":"admin","exp":4102444800}';
const payload = Buffer.from(claims).toString('base64url');
// The header and the signature stay the same; only the claims change.
return `${parts[0]}.${payload}.${parts[2]}`;
}
  • token.split('.') returns the three pieces as an array. parts[0] is the header and parts[2] is the signature.
  • The claims are in single quotes, so the double quotes of the JSON need no escaping.
  • Buffer.from(claims).toString('base64url') encodes the text as base64url, the URL-safe alphabet without = padding that JWTs use.

Step 5: Decode Both Tokens​

Decoding is one call in most libraries, and it never asks for the key. Each function below returns the claims of whatever token it gets, genuine or forged, and reads role from them.

main.js
// Decoding reads the claims without the key, and checks nothing.
function decodeRole(token) {
return decodeJwt(token).role;
}
  • decodeJwt(token) returns the payload as an object, and .role reads one claim from it.

Step 6: Verify Both Tokens​

Verifying is the verify function from the last tutorial, which now hands back the role. It needs the key, accepts only HS256, and returns claims only when the signature matches and the token hasn't expired.

main.js
// Verifying checks the signature and the expiry with the key first.
async function verifyRole(key, token) {
const { payload } = await jwtVerify(token, key, { algorithms: ['HS256'] });
return payload.role;
}
  • jwtVerify(token, key, { algorithms: ['HS256'] }) checks the signature and exp, then returns the payload.

Step 7: Put It Together​

The last function prints what decoding and verifying make of one token. Verifying a forged token raises the library's error, so the function catches it and prints the reason. The rest of the program reads JWT_SECRET, turns it into the key, creates Zara's genuine token, forges a copy and reports on both.

main.js
// Show what decoding and verifying each make of one token.
async function report(key, label, token) {
console.log(`${label} token`);
console.log(` decode says: role ${decodeRole(token)}`);
try {
console.log(` verify says: role ${await verifyRole(key, token)}`);
} catch (err) {
if (!(err instanceof errors.JOSEError)) throw err;
console.log(` verify says: rejected (${err.message})`);
}
}

// The key both services share: 32 random bytes, kept as base64 text in JWT_SECRET.
const secret = process.env.JWT_SECRET;
if (!secret) {
console.error('Set the JWT_SECRET environment variable first.');
process.exit(1);
}
const key = Uint8Array.fromBase64(secret);

const genuine = await createToken(key, 'user-42', 'Zara', 'member');
const forged = forgeToken(genuine);
console.log(`Genuine: ${genuine}`);
console.log(`Forged: ${forged}`);

await report(key, 'Genuine', genuine);
await report(key, 'Forged', forged);
  • report is async because verifyRole is, and await waits for each report before the next one starts.
  • The catch handles jose's own errors, errors.JOSEError, and throws anything else on, as in the last tutorial.

Step 8: Run the Program​

Run the program in the terminal where you set JWT_SECRET:

Terminal
node main.js
Output
Genuine: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiWmFyYSIsInJvbGUiOiJtZW1iZXIiLCJzdWIiOiJ1c2VyLTQyIiwiZXhwIjoxNzk1ODY1NjcxfQ.EWU1U89TVV9hKb0hIKQDFRT5tctw70YQCgUPhJzYiXk
Forged: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyLTQyIiwibmFtZSI6IlphcmEiLCJyb2xlIjoiYWRtaW4iLCJleHAiOjQxMDI0NDQ4MDB9.EWU1U89TVV9hKb0hIKQDFRT5tctw70YQCgUPhJzYiXk
Genuine token
decode says: role member
verify says: role member
Forged token
decode says: role admin
verify says: rejected (signature verification failed)

A zsh terminal where node main.js prints a genuine token and a forged one that share their first and last pieces; decode says role member and then role admin, and verify accepts the genuine token and rejects the forged one because the signature verification failed.

Your tokens differ from these, because your key and your clock differ, but the pattern is the same in all eight languages. Decoding reported admin for the forged token. Verifying rejected it.

The Complete File​

The complete main.js: createToken signs Zara's claims with SignJWT, forgeToken swaps in an admin payload between the same header and signature, decodeRole reads the role with decodeJwt, verifyRole checks it with jwtVerify, and report prints what each says about both tokens.

main.js
import { SignJWT, decodeJwt, jwtVerify, errors } from 'jose';

// The sign-in service's job: sign a token with the user's name and role.
async function createToken(key, userId, name, role) {
return new SignJWT({ name, role })
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setSubject(userId)
.setExpirationTime('15m')
.sign(key);
}

// What anyone can do without the key: swap in claims of their own.
function forgeToken(token) {
const parts = token.split('.');
const claims = '{"sub":"user-42","name":"Zara","role":"admin","exp":4102444800}';
const payload = Buffer.from(claims).toString('base64url');
// The header and the signature stay the same; only the claims change.
return `${parts[0]}.${payload}.${parts[2]}`;
}

// Decoding reads the claims without the key, and checks nothing.
function decodeRole(token) {
return decodeJwt(token).role;
}

// Verifying checks the signature and the expiry with the key first.
async function verifyRole(key, token) {
const { payload } = await jwtVerify(token, key, { algorithms: ['HS256'] });
return payload.role;
}

// Show what decoding and verifying each make of one token.
async function report(key, label, token) {
console.log(`${label} token`);
console.log(` decode says: role ${decodeRole(token)}`);
try {
console.log(` verify says: role ${await verifyRole(key, token)}`);
} catch (err) {
if (!(err instanceof errors.JOSEError)) throw err;
console.log(` verify says: rejected (${err.message})`);
}
}

// The key both services share: 32 random bytes, kept as base64 text in JWT_SECRET.
const secret = process.env.JWT_SECRET;
if (!secret) {
console.error('Set the JWT_SECRET environment variable first.');
process.exit(1);
}
const key = Uint8Array.fromBase64(secret);

const genuine = await createToken(key, 'user-42', 'Zara', 'member');
const forged = forgeToken(genuine);
console.log(`Genuine: ${genuine}`);
console.log(`Forged: ${forged}`);

await report(key, 'Genuine', genuine);
await report(key, 'Forged', forged);

What the Run Shows​

  • The forged token looks real. Its first and last pieces are the genuine token's, character for character. Only the middle piece changed, and it holds valid JSON with valid-looking claims.
  • Decoding believed it in every language. Each decode call returned whatever the payload said, so a program that trusts decoded claims would have treated Zara as an admin until the year 2100.
  • Verifying caught it in every language. The signature was computed over the genuine payload, so it doesn't match the forged one.
  • For the genuine token, both said the same. That's what makes decode easy to misuse. In testing, every token is genuine, so decode and verify always agree, and the difference shows only when someone sends a token you didn't create.

How Each Library Says No​

Each library rejected the forged token with the same error it gave the other app's token in the last tutorial. To a verifier, a changed payload and a wrong key look alike: either way, the signature doesn't match the header and payload it arrived with. Create and Verify a JWT in Code lists the error type to catch in each language.

.NET's name for it is the only one that points somewhere else: SecurityTokenSignatureKeyNotFoundException sounds like a missing key. Its full message starts with "IDX10517: Signature validation failed. The token's kid is missing.", because these tokens have no kid header to tell IdentityModel which key was meant. When a test gave the key and the token a kid, the same forgery raised SecurityTokenInvalidSignatureException instead, with "IDX10511: Signature validation failed." Both mean the signature didn't verify.

What You Can Do Now​

  • Tell decoding from verifying in any JWT library, by the function's name, its options or whether it takes a key.
  • Forge a token's payload yourself, to check that your own code rejects it.
  • Read a token without trusting it, to choose a key or to debug, and keep those claims away from decisions about the user.
  • Decode a JWT by hand in Java and PHP, where the library doesn't offer it.

Common Mistakes​

MistakeWhat happensDo this instead
Deciding who the user is from decoded claimsAnyone can send a token with any claims, as Step 4 didUse only the claims your library's verify call returns
Testing only with genuine tokensDecode and verify give the same claims, so the bug never showsAlso send a token with a changed payload and check that it's rejected
Leaving jwt.decode(token, options={"verify_signature": False}) in Python code that serves requestsIt skips the expiry and every other claim check, not just the signatureKeep the call with the key and algorithms
Letting the decoded header choose how to verifyThe sender decides how their own token gets checkedPin the algorithm when you verify, and use the header only to pick a key you already trust
Reading base64url with PHP's plain base64_decodeIt silently drops - and _, and the JSON comes out wrongUse JWT::urlsafeB64Decode
Splitting a token with split(".") in JavaThe dot matches every character, so you get no pieces at allUse split("\\.")

Troubleshooting​

SymptomLikely causeFix
Set the JWT_SECRET environment variable first.Step 2 ran in another terminal, or not at allRun Step 2 again in the terminal where you run the program
Java: ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 0The token was split with split(".")Use split("\\.")
Java: UnsupportedJwtException: Cannot verify JWS signature: unable to locate signature verification keyjjwt was asked to parse a signed token without a keyGive the parser the key with verifyWith(key), or decode the payload by hand as in Step 5
Rust: error[E0599]: no method named `encode` found for struct `GeneralPurpose` use base64::Engine; is missingAdd it: encode is a method of the Engine trait
C#: SecurityTokenSignatureKeyNotFoundException for a token you createdThe token was changed after it was signed, or signed with another keySee How Each Library Says No
An issue was encountered verifying workloads. For more information, run "dotnet workload update".The first dotnet command under a new user accountIt's harmless. Fixed: An issue was encountered verifying workloads explains it

Frequently Asked Questions​

Is it safe to decode a JWT in the browser?​

Yes, for reading it, for example to show the user's name or to know when the token runs out. The browser isn't the one deciding what the user may do; the API is, and it verifies every request. Remember that decoding isn't limited to your code, so never put anything in a token you'd mind its holder reading.

Does decoding check the expiry?​

No. All eight ways of decoding in this tutorial returned the claims of a token that had expired an hour earlier, without an error. Only verifying checks exp.

Why don't jjwt and php-jwt have a decode function?​

jjwt's README is clear that a token whose signature fails "cannot be safely trusted and should be discarded", and none of its parse methods reads a signed token without a key. For picking a key by kid, jjwt hands your code the header during verification, through a key Locator, so you never decode it yourself. php-jwt simply has no such function; its README shows how to read a header by hand and warns that doing so "is vulnerable to attacks".

If decoding is dangerous, why do libraries offer it?​

Because reading a token has real uses: choosing a key, refreshing a session in good time, debugging. The danger isn't in reading the claims. It's in trusting them.

Is the payload secret?​

No. Anyone who has the token can read it, as this tutorial and the first one did. A signed JWT protects the claims from being changed, not from being read. JWTs that hide their claims are encrypted JWTs, which a later tutorial covers.

Conclusion​

Decoding and verifying return the same claims for a genuine token, which is exactly why decode is so easy to misuse. Only verifying asks whether the holder of the key wrote those claims, and only verifying noticed when the payload said admin under a signature made for member. Decode a token when you need to read it; verify it before your code believes it.

Next: Registered Claims (coming soon). What iss, sub, aud, exp, nbf, iat and jti mean, and which ones your verify call should require.

Additional Resources​