JSON Web Tokens (JWTs) are a stateless way to authenticate users. A JWT contains a signed payload — the server can verify its authenticity without a database lookup.
Structure: header.payload.signature — all base64url-encoded.
const jwt = require('jsonwebtoken')
const SECRET = 'my-secret-key'
// Sign a token (e.g. at login)
const token = jwt.sign({ userId: 42, role: 'admin' }, SECRET, { expiresIn: '1h' })
// ...1. Sign a JWT with payload { userId: 1, role: "user" } and secret "nextsecret" that expires in 1 hour
2. Verify it and print "User ID: 1"
3. Try to verify a tampered token "bad.token.here" and print "Invalid token"
JSON Web Tokens (JWTs) are a stateless way to authenticate users. A JWT contains a signed payload — the server can verify its authenticity without a database lookup.
Structure: header.payload.signature — all base64url-encoded.
const jwt = require('jsonwebtoken')
const SECRET = 'my-secret-key'
// Sign a token (e.g. at login)
const token = jwt.sign({ userId: 42, role: 'admin' }, SECRET, { expiresIn: '1h' })
// ...1. Sign a JWT with payload { userId: 1, role: "user" } and secret "nextsecret" that expires in 1 hour
2. Verify it and print "User ID: 1"
3. Try to verify a tampered token "bad.token.here" and print "Invalid token"