Skip to main content

What Is a JWT?

A JSON Web Token, or JWT, is a short piece of signed JSON that one system hands to another to say who someone is and what they may do. This first tutorial of the JWT course builds one by hand in the terminal, reads it back, checks its signature, and watches the check fail when one word in it changes. You'll see every byte of a token before any library hides them.

What a JWT Does​

RFC 7519, the standard that defines it, puts it in one sentence: "JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties." A claim is a statement, such as "this is user asha" or "this token expires at 10:30". The token carries the claims, and a signature proves who wrote them.

You meet JWTs whenever an app signs you in and then calls an API for you:

  • Web and mobile apps. After you sign in, the app sends a token with every request, in an Authorization: Bearer <token> header. The API reads who you are from the token instead of asking you again.
  • "Sign in with…" buttons. OpenID Connect, the protocol behind most of them, returns an ID token about you, and the ID token is a JWT.
  • Cloud platforms. Microsoft Entra ID issues JWT access tokens; How to Get an Access Token for Your Own API with the Azure CLI shows one and its claims.

The idea that makes all of this work: anyone can read a JWT, but nobody can change it without the key that signed it.

How a JWT Works​

A server that signs people in writes their claims into a token and signs it. The app keeps the token and sends it with each request, and the API checks the signature before it believes anything inside:

The API doesn't look anything up: the token carries the claims, and the signature proves them. That makes JWTs fast to check and easy to pass between services. It also means a token stays usable until it expires, which later tutorials in this course deal with.

The Three Parts​

Every JWT you'll build in this tutorial looks like this: three parts joined by dots.

A JSON Web Token split into its three colour-coded parts, header, payload and signature, joined by dots, with the decoded header JSON, the decoded payload claims, and the HMACSHA256 formula that makes the signature from the first two parts and a secret.

  • The header is JSON that says how the token is signed, such as {"alg":"HS256","typ":"JWT"}.
  • The payload is JSON with the claims.
  • The signature is made from the first two parts and a key. Change one character of either, and it no longer matches.

The first two parts are encoded with base64url, a way of writing any data with only letters, digits, - and _, so the token fits in a web address or an HTTP header. Encoding isn't encryption: anyone can turn it back into the JSON. A signed JWT is signed, not encrypted.

The JOSE Family​

JWTs are one of five related standards, which RFC 7165 calls JSON Object Signing and Encryption (JOSE). You'll meet all of them in this course:

StandardWhat it coversDefined in
JWT, JSON Web TokenThe token and its claimsRFC 7519
JWS, JSON Web SignatureSigning content. A signed JWT is a JWS.RFC 7515
JWE, JSON Web EncryptionEncrypting content. An encrypted JWT is a JWE, with five parts.RFC 7516
JWK, JSON Web KeyWriting keys as JSONRFC 7517
JWA, JSON Web AlgorithmsThe algorithm names, such as HS256, RS256 and ES256RFC 7518

The Example​

A book club website signs in a member named Asha. Her token says who she is, that she's a member, when it was issued, and that it expires an hour later. The site signs it with HS256, which is HMAC with SHA-256, and a secret that only the site knows.

You'll build that token with the same steps a JWT library performs, using only the terminal: OpenSSL on macOS and Linux, and PowerShell on Windows. Then you'll play the part of someone who changes Asha's role to admin, and watch the signature catch it.

Prerequisites​

  • macOS or Linux: OpenSSL. macOS includes it, and most Linux distributions do too; check with openssl version. The outputs below come from OpenSSL 3.5.9, and every step also works with the LibreSSL openssl built into macOS.
  • Windows: PowerShell 7.6, the current long-term support release. Check with $PSVersionTable.PSVersion.

Every step runs in the same terminal window: the variables you create in one step are used in the next. If you close the window, start again from Step 1.

Step 1: Write the Header​

The header says how the token is signed.

Terminal
header='{"alg":"HS256","typ":"JWT"}'
echo "$header"
Output
{"alg":"HS256","typ":"JWT"}

alg names the signing algorithm, here HS256, and typ says the object is a JWT. The single quotes keep the double quotes inside the JSON as they are.

Step 2: Write the Payload​

The payload holds Asha's claims. Two of them are times, written as Unix time: the number of seconds since 1 January 1970 UTC. The token is issued now and expires 3,600 seconds, one hour, later. How to Get the Current Unix Time in the Terminal explains the command that gets the time.

Terminal
now=$(date +%s)
payload=$(printf '{"sub":"asha","name":"Asha","role":"member","iat":%d,"exp":%d}' "$now" "$((now + 3600))")
echo "$payload"
Output
{"sub":"asha","name":"Asha","role":"member","iat":1795599390,"exp":1795602990}

printf fills each %d with a number: the time now, then the time plus 3,600.

Your times will be different. The claims mean:

ClaimMeaning
subThe subject. RFC 7519: "The "sub" (subject) claim identifies the principal that is the subject of the JWT." Here, the user asha.
name, roleThe app's own claims: her display name and her role in the book club.
iatIssued at: when the token was made.
expExpiration time: after this, the token must not be accepted.

sub, iat and exp are registered claim names that RFC 7519 defines, so every JWT library knows them. A later tutorial covers all the registered claims.

Step 3: Encode Both Parts with Base64url​

Base64url turns the JSON into letters, digits, - and _. In bash and zsh, a one-line function does it: standard base64 from OpenSSL, then tr swaps the two characters that base64url changes and deletes the = padding. How to Base64url Encode Text in the Terminal explains each part.

Terminal
b64url() { openssl base64 -A | tr '+/' '-_' | tr -d '='; }
header_b64=$(printf '%s' "$header" | b64url)
payload_b64=$(printf '%s' "$payload" | b64url)
echo "$header_b64"
echo "$payload_b64"
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEiLCJyb2xlIjoibWVtYmVyIiwiaWF0IjoxNzk1NTk5MzkwLCJleHAiOjE3OTU2MDI5OTB9

printf '%s' hands the JSON to b64url exactly as it is. echo would add a line break at the end, the line break would be encoded too, and the token would be wrong.

The header always encodes to eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9, because it's always the same text. That's also why so many tokens start with eyJ: it's how {" looks in base64.

Step 4: Sign the Two Parts​

The signature is an HMAC-SHA256 of the two encoded parts joined by a dot, header.payload, made with a secret key. First, the site needs its secret: 32 random bytes, the size the standard requires for HS256. How to Generate a Secret Key for HS256 JWTs in the Terminal covers why.

Terminal
secret=$(openssl rand -base64 32)
echo "$secret"
signature=$(printf '%s' "$header_b64.$payload_b64" | openssl dgst -sha256 -hmac "$secret" -binary | b64url)
echo "$signature"
Output
Dmkyg+U2gZl7Pa3oemOT6tU8WKjoF1sg/P/rd3SxyGA=
QYwN6T1o_2D53o3fP_edC_gLc1XfB0bLDH7cgT5AQcQ

openssl dgst -sha256 -hmac "$secret" computes the HMAC with the secret as its key, -binary keeps it as raw bytes, and b64url encodes them like the other two parts.

The secret is printed here only so you can see one. A real app never prints, logs or shares its secret: whoever has it can sign tokens of their own. How to Create an HMAC-SHA256 Signature in the Terminal shows HMAC on its own, checked against the standard's test values.

Step 5: Put the Token Together​

Join the three parts with dots:

Terminal
token="$header_b64.$payload_b64.$signature"
echo "$token"
Output
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEiLCJyb2xlIjoibWVtYmVyIiwiaWF0IjoxNzk1NTk5MzkwLCJleHAiOjE3OTU2MDI5OTB9.QYwN6T1o_2D53o3fP_edC_gLc1XfB0bLDH7cgT5AQcQ

A zsh terminal showing the b64url function, the encoded header and payload, a random secret, the HMAC-SHA256 signature, and the finished token: three base64url parts joined by dots.

That's a complete, valid JWT. Any JWT library given the same secret accepts it until its exp time passes.

Step 6: Read the Token Back​

Now take the token apart the way anyone who receives it can. Decoding needs one extra step: JWTs leave out base64's = padding, and OpenSSL's decoder needs it, so the function puts it back before decoding. How to Decode Base64url Text in the Terminal explains the padding rule.

Terminal
b64url_decode() {
local data
data=$(printf '%s' "$1" | tr '_-' '/+')
while [ $(( ${#data} % 4 )) -ne 0 ]; do data="$data="; done
printf '%s' "$data" | openssl base64 -d -A
echo
}
b64url_decode "$(echo "$token" | cut -d. -f1)"
b64url_decode "$(echo "$token" | cut -d. -f2)"
Output
{"alg":"HS256","typ":"JWT"}
{"sub":"asha","name":"Asha","role":"member","iat":1795599390,"exp":1795602990}

cut -d. -f1 takes the part before the first dot, and -f2 the part after it. The function swaps - and _ back, adds = until the length is a multiple of 4, and decodes.

A zsh terminal where the b64url_decode function turns the token's first part back into the header JSON and its second part back into Asha's claims.

No key was needed. Anyone who sees a JWT can read everything in its payload, so never put a password, a secret or private data there.

Leaving out the padding fails without a word

Skip the padding, and openssl base64 -d may print part of the payload, or nothing, and still report success. Asha's payload happens to be 104 characters, a multiple of 4, so it would decode either way, but most tokens aren't that lucky. Fixed: openssl base64 -d Cuts Off a JWT Payload or Prints Nothing shows it happening.

Step 7: Check the Signature​

To check a token, the API does what the site did in Step 4: it signs the token's first two parts with the same secret, and compares the result with the token's third part.

Terminal
check_signature() {
local data expected
data=$(echo "$1" | cut -d. -f1-2)
expected=$(printf '%s' "$data" | openssl dgst -sha256 -hmac "$secret" -binary | b64url)
if [ "$expected" = "$(echo "$1" | cut -d. -f3)" ]; then
echo "Signature OK"
else
echo "Signature does NOT match"
fi
}
check_signature "$token"
Output
Signature OK

cut -d. -f1-2 keeps the first two parts with the dot between them: exactly the text that was signed.

The signatures match, so the token was made with this secret and hasn't changed. A real API also checks the times, and more: later tutorials build that up claim by claim.

Step 8: Change One Claim and Check Again​

Now play the attacker. Take Asha's payload, change her role from member to admin, and keep the original signature, because without the secret you can't make a new one:

Terminal
fake_payload=$(printf '%s' "$payload" | sed 's/"role":"member"/"role":"admin"/')
fake_payload_b64=$(printf '%s' "$fake_payload" | b64url)
fake_token="$header_b64.$fake_payload_b64.$signature"
b64url_decode "$(echo "$fake_token" | cut -d. -f2)"
check_signature "$fake_token"
Output
{"sub":"asha","name":"Asha","role":"admin","iat":1795599390,"exp":1795602990}
Signature does NOT match

sed 's/old/new/' replaces the first text with the second.

A zsh terminal where the check_signature function prints Signature OK for the real token, then a token whose role was changed to admin decodes fine but prints Signature does NOT match.

The changed token decodes perfectly: it really does say admin. But its signature belongs to the old payload, so the check fails and an API would reject it. That's the whole job of the signature: anyone can read the claims, and nobody can change them without the secret.

The Complete Script​

Here is everything in one file, to run again whenever you like. It doesn't print the secret.

The complete make-jwt.sh script in a macOS-style editor window: the b64url, b64url_decode and check_signature functions, then the steps that write, encode, sign, read and check the token, and change one claim.

make-jwt.sh
#!/usr/bin/env bash
# Build a JSON Web Token (JWT) by hand, read it back and check its signature.

# Base64url: base64, then '+' becomes '-', '/' becomes '_', and the '=' padding goes.
b64url() { openssl base64 -A | tr '+/' '-_' | tr -d '='; }

# Turn base64url text back into the original text (the '=' padding goes back first).
b64url_decode() {
local data
data=$(printf '%s' "$1" | tr '_-' '/+')
while [ $(( ${#data} % 4 )) -ne 0 ]; do data="$data="; done
printf '%s' "$data" | openssl base64 -d -A
echo
}

# Sign the token's first two parts again and compare the result with its third part.
check_signature() {
local data expected
data=$(echo "$1" | cut -d. -f1-2)
expected=$(printf '%s' "$data" | openssl dgst -sha256 -hmac "$secret" -binary | b64url)
if [ "$expected" = "$(echo "$1" | cut -d. -f3)" ]; then
echo "Signature OK"
else
echo "Signature does NOT match"
fi
}

# 1. The header and the payload
header='{"alg":"HS256","typ":"JWT"}'
now=$(date +%s)
payload=$(printf '{"sub":"asha","name":"Asha","role":"member","iat":%d,"exp":%d}' "$now" "$((now + 3600))")

# 2. Encode them, sign them and put the token together
header_b64=$(printf '%s' "$header" | b64url)
payload_b64=$(printf '%s' "$payload" | b64url)
secret=$(openssl rand -base64 32)
signature=$(printf '%s' "$header_b64.$payload_b64" | openssl dgst -sha256 -hmac "$secret" -binary | b64url)
token="$header_b64.$payload_b64.$signature"
echo "Token: $token"

# 3. Read the token back
b64url_decode "$(echo "$token" | cut -d. -f1)"
b64url_decode "$(echo "$token" | cut -d. -f2)"

# 4. Check the signature, then change one claim and check again
check_signature "$token"
fake_payload=$(printf '%s' "$payload" | sed 's/"role":"member"/"role":"admin"/')
fake_payload_b64=$(printf '%s' "$fake_payload" | b64url)
fake_token="$header_b64.$fake_payload_b64.$signature"
check_signature "$fake_token"

Save it as make-jwt.sh and run it with bash or zsh:

Terminal
bash make-jwt.sh
Output
Token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhc2hhIiwibmFtZSI6IkFzaGEiLCJyb2xlIjoibWVtYmVyIiwiaWF0IjoxNzk1NTk5NDU5LCJleHAiOjE3OTU2MDMwNTl9.znyyDrFCy6HtNCI9BEezAz2pmwQOvrWj_UjnTFR288s
{"alg":"HS256","typ":"JWT"}
{"sub":"asha","name":"Asha","role":"member","iat":1795599459,"exp":1795603059}
Signature OK
Signature does NOT match

Every run makes a new secret and a new time, so every run prints a new token. The header, the claims and the two results stay the same.

What You Can Do Now​

  • Recognise a JWT: three base64url parts joined by dots, usually starting with eyJ.
  • Read any token's header and payload without a key, and know that what you read proves nothing until the signature is checked.
  • Explain what HS256 signs: the encoded header and payload, with a secret, and why changing one claim breaks the signature.

Every Concept, and Where This Course Teaches It​

The JWT course teaches one concept per tutorial, in the order you need them. Each becomes a link here when its tutorial is out.

Fundamentals​

#TutorialWhat you'll learn
1What Is a JWT? (this page)The three parts, base64url, and an HS256 token built and checked by hand
2Create and Verify a JWT in Code (coming soon)The same token with a JWT library in JavaScript, Python, C#, Java, Go, PHP, Ruby and Rust
3Decode vs Verify (coming soon)Why reading a token proves nothing, and what each library's "decode" really does
4Registered Claims (coming soon)iss, sub, aud, exp, nbf, iat and jti
5Custom Claims (coming soon)Public and private claims, and what never to put in a token
6Expiry, Not-Before and Clock Skew (coming soon)Time claims, and computers whose clocks disagree
7HMAC Signatures and Secrets (coming soon)HS256, HS384 and HS512, and handling the secret
8RSA Signatures (coming soon)RS256 and PS256, key pairs and PEM files
9ECDSA Signatures (coming soon)ES256, ES384 and ES512
10Ed25519 Signatures (coming soon)EdDSA and the newer fully specified algorithm names
11Choosing an Algorithm (coming soon)Sizes and speeds measured, symmetric or asymmetric
12The JOSE Header (coming soon)alg, typ, kid, cty, crit, and the dangerous jku, jwk, x5u and x5c
13Validate a JWT Properly (coming soon)The full checklist, from the JWT best-practice standard
14JSON Web Keys (coming soon)Keys as JSON, and key thumbprints
15JWKS: Publish and Fetch Public Keys (coming soon)Key sets, kid lookups and caching
16Rotate Signing Keys (coming soon)Changing keys without signing anyone out
17Encrypted JWTs (JWE) (coming soon)Five-part tokens that hide their claims
18Nested JWTs (coming soon)Sign, then encrypt
19Send a JWT over HTTP (coming soon)Authorization: Bearer, 401 and 403, WWW-Authenticate
20Access and Refresh Tokens (coming soon)Why apps use two tokens
21Refresh Token Rotation (coming soon)Detecting a stolen refresh token
22Revoke Tokens and Log Out (coming soon)Taking a token back before it expires
23JWTs in the Browser (coming soon)Cookies or storage, XSS and CSRF, and the backend-for-frontend pattern
24JWTs Between Services (coming soon)Service-to-service tokens and audiences
25When Not to Use a JWT (coming soon)Sessions, opaque tokens and PASETO
26JWS JSON Serialization (coming soon)Detached payloads and other forms of JWS
27Selective Disclosure JWTs (coming soon)SD-JWT, which reveals only some claims
28Post-Quantum JWTs (coming soon)ML-DSA signatures
29CWT and COSE (coming soon)The binary cousins of JWT and JOSE

The Other Tracks​

  • Attacks and Defenses (coming soon): the none algorithm, algorithm confusion, cracking weak secrets, unverified tokens, header injection, stolen and replayed tokens, and a security checklist. Each attack runs against a weak demo on your own computer, and then gets fixed.
  • JWT in OAuth 2.0 and OpenID Connect (coming soon): ID tokens, JWT access tokens, client assertions, DPoP, token exchange and more, with a free local Keycloak server.
  • Real-World JWTs (coming soon): checking tokens from identity providers such as Microsoft Entra ID, Auth0 and Google; creating the JWTs that services such as GitHub Apps and Apple's APIs require; checking tokens at an API gateway.

The Product Lines​

After the fundamentals, each product line builds a small JWT authentication API in one language, one concept at a time: signing in, protecting endpoints, roles, refresh tokens, signing out, public keys and key rotation. Lines are planned for Node.js with TypeScript, Python with FastAPI, C# with ASP.NET Core, Java with Spring Boot, Go, PHP, Ruby on Rails, Rust with Axum, and Kotlin with Ktor (coming soon).

What It Costs​

Nothing. OpenSSL and PowerShell are free, and everything in this tutorial runs on your own computer. Later tutorials that use a cloud identity provider will say so at the top, along with any free plan.

Common Mistakes​

MistakeWhat happensDo this instead
Thinking a JWT is encryptedPrivate data in the payload is readable by anyoneTreat the payload as public
Trusting a decoded payloadAnyone can write any claimsCheck the signature, and the times, first
Using echo to encodeA hidden line break becomes part of the tokenUse printf '%s'
Comparing signatures with -eq in PowerShellLetter case is ignoredUse -ceq
Pasting real tokens into websites to read themAnyone who sees the token can use it until it expiresDecode it on your own computer, as in Step 6

Troubleshooting​

SymptomLikely causeFix
The decoded payload is cut off or emptyThe = padding wasn't put backUse b64url_decode or ConvertFrom-Base64Url as written
Signature does NOT match for your own tokenThe terminal was closed or secret changed, so the token was made with a different secretRun the steps again in one window, or run the complete script
PowerShell: The term 'ConvertFrom-Base64Url' is not recognized…The function wasn't defined in this sessionPaste the function again, then the command
command not found: b64urlThe function wasn't defined in this terminalPaste the b64url line from Step 3 again

Frequently Asked Questions​

How do you pronounce JWT?​

RFC 7519 says: "The suggested pronunciation of JWT is the same as the English word "jot"."

Is a JWT encrypted?​

A signed JWT, the kind this page built, is not: anyone can read it. JWTs can also be encrypted, using JWE, which a later tutorial covers.

Why do so many tokens start with eyJ?​

Their header is JSON, so it starts with {", and {" encodes to eyJ in base64url.

Do I need a library to use JWTs?​

For real apps, yes. Building tokens by hand shows how they work, but a good library also checks the algorithm, the times and much more. The next tutorial uses libraries in eight languages.

Is HS256 the only way to sign a JWT?​

No. HS256 uses one shared secret. Algorithms such as RS256, ES256 and Ed25519 sign with a private key and check with a public one, so the apps that check tokens can't create them. Later tutorials cover each.

Conclusion​

A JWT is a header, a payload and a signature, each base64url-encoded and joined by dots. You built one by hand: you wrote the JSON, encoded it, signed it with HMAC-SHA256 and a secret, read it back without any key, and saw the signature reject a token whose role was changed. Every JWT library performs those same steps, with many more checks around them.

Next: Create and Verify a JWT in Code (coming soon) — the same token, made and checked with a JWT library in JavaScript, Python, C#, Java, Go, PHP, Ruby and Rust.

Additional Resources​