Skip to main content

Create and Verify a JWT in Code

In What Is a JWT? you built a token by hand: a header, a payload, base64url, an HMAC signature, and eight terminal steps to check it. Real programs hand all of that to a JWT library, where one call creates a signed token and one call verifies it. This tutorial writes the same small program in eight languages, each with its language's most-used JWT library, and watches every one of them turn down a token signed with the wrong secret.

What a JWT Library Does​

A JWT library does two jobs, and every library in this tutorial gives each job its own call.

Creating a token. You give it the claims, a key and an algorithm. It writes the header, turns the header and the claims into base64url, signs both parts and joins the three pieces with dots. Those are the steps you typed one by one in the first tutorial.

Verifying a token. You give it the token, the same key and the algorithms you accept. It splits the token, refuses any algorithm you didn't list, works out the signature again from the first two parts and compares it with the one in the token. Then it checks the time claims, such as exp. You only get the claims back when every check passes. Otherwise you get an error, and your code must stop there.

Reading a token isn't verifying it. Anyone can decode a payload with a few terminal commands, as the first tutorial showed. Only verifying proves that someone who holds the key signed the token and that nobody has changed it since.

How a Token Travels Between Two Services​

With HS256, the key that signs a token is also the key that verifies it, so both services hold the same secret. The app in the middle never needs it. It only carries the token.

The Eight Libraries​

Each language uses its most-used JWT library that's still maintained. These are the numbers each package registry showed on 26 November 2026:

LanguageLibraryVersionWhy this one
JavaScript (Node.js 26)jose6.2.18About 242 million npm downloads a week, against 84 million for jsonwebtoken, and no dependencies of its own
Python 3.15PyJWT2.15.1About 776 million downloads last month, five times more than the next Python JWT library
C# (.NET 10)Microsoft.IdentityModel.JsonWebTokens8.23.0Microsoft's JsonWebTokenHandler, which ASP.NET Core's JWT bearer authentication has used by default since ASP.NET Core 8
Java 25jjwt0.13.0206 projects depend directly on its newest version, against 182 for Nimbus JOSE + JWT's newest
Go 1.27golang-jwt/jwt/v55.3.1Imported by 19,155 Go packages, against 889 for go-jose/v4
PHP 8.6firebase/php-jwt7.2.2About 25 million installs a month, against 17 million for lcobucci/jwt
Ruby 4.0jwt3.3.1The Ruby JWT gem, downloaded 849 million times
Rust 1.100jsonwebtoken12.0.0About 80 million downloads in the last 90 days, against 1.6 million for jwt-simple

The Example​

A small online shop runs two services. When Zara signs in, the sign-in service gives her app a token that says she's user-42 and lasts 15 minutes. Each time the app asks the orders API for her orders, it sends that token, and the API verifies it before it answers.

The program you'll write plays both parts. Its createToken function does the sign-in service's job, and its verifyToken function does the API's. Then it does what every API has to survive: it receives a token from somewhere else, with the same claims but signed with another app's key, and turns it down. It prints three lines:

What the program prints
Token: <the token it made for Zara>
Verified: Zara (user-42), expires at <the exp claim>
Rejected: a token signed with another secret (<the library's reason>)

Every language uses the same folder name, jwt-demo, the same claims and the same three lines, so you can switch tabs and compare them.

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 jwt-demo and cd jwt-demo, 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 jwt-demo
cd jwt-demo
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/jwt-demo/package.json:
{
"name": "jwt-demo",
"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 993ms
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": "jwt-demo",
"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. Every program decodes that text back into the same 32 bytes and uses them as the key, so all eight programs share one key and a token from one can be checked by another. 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 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 three steps, and the complete file shows it all together.

The first piece is the sign-in service's job. It takes the key, a user ID and a name, and returns a signed token with four claims: sub, who the token is about; name; iat, when it was issued; and exp, when it expires, 15 minutes later.

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

// The sign-in service's job: sign a token that says who the user is.
async function createToken(key, userId, name) {
return new SignJWT({ name })
.setProtectedHeader({ alg: 'HS256', typ: 'JWT' })
.setSubject(userId)
.setIssuedAt()
.setExpirationTime('15m')
.sign(key);
}
  • new SignJWT({ name }) starts a token with your own claims. Here that's name.
  • .setProtectedHeader({ alg: 'HS256', typ: 'JWT' }) writes the header. jose writes exactly the header you give it, so typ is there only because the code sets it.
  • .setSubject(), .setIssuedAt() and .setExpirationTime('15m') add sub, iat and exp. jose reads '15m' as 15 minutes from now.
  • .sign(key) signs with the key's bytes and gives back a promise of the token, which is why the function is async.

Step 4: Write the Code That Verifies a Token​

The second piece is the orders API's job. It takes the same key and a token, and returns the claims only when the token passes. Every version names HS256 as the one algorithm it accepts. That matters: a verifier that lets a token choose its own algorithm can be tricked into accepting a forged one.

main.js
// The orders API's job before it answers: check the signature and the expiry.
async function verifyToken(key, token) {
const { payload } = await jwtVerify(token, key, { algorithms: ['HS256'] });
return payload;
}
  • jwtVerify checks the signature and the time claims, and returns the payload with the header. The code keeps payload.
  • algorithms: ['HS256'] pins the algorithm. Without it, jose accepts every algorithm that fits the key. It never accepts alg: "none".
  • When a check fails, jose throws an error that is a JOSEError.

Step 5: Put It Together​

The rest of the program reads JWT_SECRET, stops with a message when it's missing, and decodes the base64 text into the key. Then it creates a token for Zara, verifies it, and tries a token from another app.

main.js
// 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 token = await createToken(key, 'user-42', 'Zara');
console.log(`Token: ${token}`);

const claims = await verifyToken(key, token);
console.log(`Verified: ${claims.name} (${claims.sub}), expires at ${claims.exp}`);

// A token from somewhere else: the same claims, signed with another app's key.
// That key is in the code only to stand in for the other app.
const otherKey = Uint8Array.fromBase64('D1uCGBiA0w/By+fCgdtYNZ9c9YwFwt9HmT1EvTGxCu4=');
const otherToken = await createToken(otherKey, 'user-42', 'Zara');
try {
await verifyToken(key, otherToken);
} catch (err) {
if (!(err instanceof errors.JOSEError)) throw err;
console.log(`Rejected: a token signed with another secret (${err.message})`);
}
  • process.env.JWT_SECRET reads the variable, and Uint8Array.fromBase64 turns the base64 text back into the 32 bytes. It throws a SyntaxError when the text isn't base64.
  • await works outside a function because the project is an ES module.
  • The catch checks that the error is a JOSEError and throws anything else again, so a bug in your own code isn't mistaken for a bad token.

Step 6: Run the Program​

Run it from the jwt-demo folder, in the same terminal where you set JWT_SECRET.

node main.js runs the file:

Terminal
node main.js
Output
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiWmFyYSIsInN1YiI6InVzZXItNDIiLCJpYXQiOjE3OTU2Njc0NDEsImV4cCI6MTc5NTY2ODM0MX0.T6mUqrDaOAWSfjRql5IVT4PLD1w18Geb9DpI4IPvnnM
Verified: Zara (user-42), expires at 1795668341
Rejected: a token signed with another secret (signature verification failed)

A zsh terminal where node main.js prints a token, verifies it for Zara, user-42, and rejects a token signed with another secret because the signature verification failed.

Your token and its exp will differ, because they depend on your secret and the time you run it. The other two lines will match.

The Complete File​

The complete main.js: createToken signs Zara's claims with jose's SignJWT, verifyToken checks them with jwtVerify and HS256 only, and the program decodes JWT_SECRET, verifies a token and rejects one signed with another key.

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

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

// The orders API's job before it answers: check the signature and the expiry.
async function verifyToken(key, token) {
const { payload } = await jwtVerify(token, key, { algorithms: ['HS256'] });
return payload;
}

// 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 token = await createToken(key, 'user-42', 'Zara');
console.log(`Token: ${token}`);

const claims = await verifyToken(key, token);
console.log(`Verified: ${claims.name} (${claims.sub}), expires at ${claims.exp}`);

// A token from somewhere else: the same claims, signed with another app's key.
// That key is in the code only to stand in for the other app.
const otherKey = Uint8Array.fromBase64('D1uCGBiA0w/By+fCgdtYNZ9c9YwFwt9HmT1EvTGxCu4=');
const otherToken = await createToken(otherKey, 'user-42', 'Zara');
try {
await verifyToken(key, otherToken);
} catch (err) {
if (!(err instanceof errors.JOSEError)) throw err;
console.log(`Rejected: a token signed with another secret (${err.message})`);
}

What Each Library Put in the Token​

Decode the first two parts of each token, as you did by hand in the first tutorial, and the eight libraries turn out to write slightly different JSON:

LibraryHeaderClaims, in the order written
jose{"alg":"HS256","typ":"JWT"}, as the code set itname, sub, iat, exp
PyJWT{"alg":"HS256","typ":"JWT"}sub, name, iat, exp
JsonWebTokenHandler{"alg":"HS256","typ":"JWT"}exp, sub, name, iat, nbf
jjwt{"alg":"HS256"}sub, name, iat, exp
golang-jwt{"alg":"HS256","typ":"JWT"}name, sub, exp, iat
php-jwt{"typ":"JWT","alg":"HS256"}sub, name, iat, exp
jwt (Ruby){"alg":"HS256"}sub, name, iat, exp
jsonwebtoken (Rust){"typ":"JWT","alg":"HS256"}sub, name, iat, exp

All eight are valid HS256 tokens. A verifier doesn't rebuild the JSON: it checks the signature over the exact characters it received, so the order of the keys and an optional typ make no difference. .NET is the only library that added a claim the code didn't ask for, nbf. With all eight programs given the same JWT_SECRET, PyJWT verified every one of their tokens.

How Each Library Says No​

The third line of the output is each library's own way of rejecting the token from the other app. This is the error to catch in your own code:

LibraryIts messageWhat your code catches
josesignature verification failedJWSSignatureVerificationFailed, a JOSEError
PyJWTSignature verification failedInvalidSignatureError, a jwt.InvalidTokenError
JsonWebTokenHandler(the program prints the type)SecurityTokenSignatureKeyNotFoundException, a SecurityTokenException
jjwtJWT signature does not match locally computed signature. JWT validity cannot be asserted and should not be trusted.SignatureException, a JwtException
golang-jwttoken signature is invalid: signature is invalidan error that matches jwt.ErrTokenSignatureInvalid
php-jwtSignature verification failedSignatureInvalidException, an UnexpectedValueException
jwt (Ruby)Signature verification failedJWT::VerificationError, a JWT::DecodeError
jsonwebtoken (Rust)InvalidSignaturean Error whose kind is ErrorKind::InvalidSignature

Catch the broad type, such as JOSEError or JWT::DecodeError, when any bad token should get the same answer: a 401 Unauthorized from an API. Catch the narrow one only when you treat one failure differently.

What You Can Do Now​

  • Create a signed HS256 token with your language's most-used JWT library, with sub, iat, exp and claims of your own.
  • Verify a token with the algorithm pinned, and get its claims back only when it passes.
  • Recognise your library's rejection and catch only the token errors it throws.
  • Keep the secret out of the code and off the screen, and turn its base64 text into the same key bytes in any language.

Common Mistakes​

MistakeWhat happensDo this instead
Decoding a token instead of verifying itYou trust claims anyone could have writtenAlways call the library's verify function, with the key
Leaving out the algorithm list when verifyingPyJWT refuses to run, and jose accepts every algorithm that fits the keyName HS256, or whichever algorithm you sign with
Using the secret's text as the key in one service and its decoded bytes in anotherEvery token fails verification, because the two keys differDecide what the key bytes are and decode the secret the same way everywhere
A short or made-up secretAnyone with one of your tokens can test guesses against it offlineUse 32 random bytes, as Step 2 does
Putting the secret in the codeIt ends up in Git and in every copy of the programRead it from an environment variable or a secret store
Printing IdentityModel's whole error message in .NETThe message names the key by a SHA-256 thumbprint of the secretLog the exception's type
Adding jsonwebtoken 12 to a Rust project without rust_crypto or aws_lc_rsThe crate has no cryptography to sign or verify withcargo add jsonwebtoken --features rust_crypto

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
Node.js: SyntaxError: Found a character that cannot be part of a valid base64 string.JWT_SECRET isn't base64 textSet it with the command from Step 2
Python: binascii.Error: Only base64 data is allowedJWT_SECRET isn't base64 textSet it with the command from Step 2
Python: It is required that you pass in a value for the "algorithms" argument when calling decode().jwt.decode was called without algorithmsAdd algorithms=["HS256"]
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
Go prints go: downloading github.com/golang-jwt/jwt v3.2.2+incompatibleGo checks the shorter module path tooNothing to fix. Only v5 goes into go.mod

Frequently Asked Questions​

Can a token made in one language be verified in another?​

Yes, when both use the same algorithm and the same key bytes. That's how mixed teams run a sign-in service in one language and APIs in others. With one JWT_SECRET for all eight programs, PyJWT verified the tokens every one of them created.

Why does each library write a different header?​

The standard leaves room. RFC 7519 makes typ optional, and JSON doesn't fix the order of keys. jjwt and the Ruby gem leave typ out, and php-jwt and the Rust crate write it first. None of that changes whether a token verifies, because the signature covers the exact text the token carries.

Which library should I use?​

The one in this tutorial's table for your language, unless your framework already uses another. ASP.NET Core's JWT bearer authentication, for example, uses JsonWebTokenHandler for you. Stay away from libraries that are no longer maintained, and keep the one you pick up to date, because JWT libraries get security fixes.

Is HS256 right for my app?​

It is when every service that verifies tokens may also hold the secret, as in this example. When others must verify your tokens without being able to create them, use an algorithm with a key pair, such as RS256, ES256 or EdDSA, where only the private key can sign. Later tutorials in this course cover them.

Why does the .NET version turn off the issuer and audience checks?​

TokenValidationParameters checks both by default, and this token has no iss or aud claim yet. Leaving the checks on would reject every token here. Registered Claims, the fourth Fundamentals tutorial, adds both claims and turns the checks back on.

Conclusion​

A JWT library turns the first tutorial's eight terminal steps into two calls: one that signs the claims with your key and one that verifies a token before you trust a word of it. In all eight languages the pattern is the same: keep the secret outside the code, decode it into the key bytes, pin the algorithm when you verify, and treat any error from the verify call as "this token isn't valid". Each library writes its tokens a little differently, yet they all verify one another's, because they follow the same standard.

Next: Decode vs Verify (coming soon). What each library's "decode" function really does, and why reading a token proves nothing.

Additional Resources​