generate jwt token

To generate jwt token text, encode a header and a payload as base64url, then append a signature over those two parts. The result is one string with two dots in it. RFC 7519 calls that string a JSON Web Token: a set of claims encoded in a JSON Web Signature (JWS) or a JSON Web Encryption (JWE), so the claims can be signed, MACed, or encrypted.

The token an API usually wants is the signed form, a JWS in compact serialization. The payload is readable by anyone who has the string. The signature lets a receiver detect changes to the header or payload made after the issuer applied the key. Encryption is a separate object, a JWE. The rest of this article is about the signed form.

You generate one after you have already checked the caller. A login handler can put a user id in the payload and sign it. A service can sign a token that another service will verify. The check uses the shared HMAC secret or the issuer’s public key, and it does not require the receiver to have stored that token. A session cookie works the other way around. The cookie holds an id, and the server looks the session up. A signed JWT carries the claims itself, so throwing the token away on the server does not make it stop working. It stops working at exp, or earlier if you keep a list of jti values to refuse. RFC 7519 says jti can be used to prevent a replay.

Anatomy of a JWT

A compact signed token has three parts.

header.payload.signature

Each part is base64url, defined in RFC 7515 as base64 with the URL-safe alphabet, with = padding removed and with no line breaks. + and / become - and _. That is an encoding. It is not encryption. Anyone can decode the first two parts.

The header JSON is {"alg":"HS256","typ":"JWT"} and the payload JSON is {"sub":"1234567890","name":"John Doe","iat":1516239022}. HMAC-SHA-256 over the ASCII string base64url(header) + "." + base64url(payload), using the 19-byte key your-256-bit-secret, produces this token. The first segment decodes back to that header, and the second decodes back to that payload.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

alg is the MAC or signature algorithm. HS256 means HMAC using SHA-256. typ is optional. When it is present, RFC 7519 recommends the uppercase value JWT. When the payload is an object, jsonwebtoken 9 sets typ to JWT. kid is optional too. RFC 7515 defines it as a case-sensitive string that hints which key secured the token. Receivers use it to pick a key once more than one key is valid.

Payload

The payload is a JSON object. The names are claims. RFC 7519 defines three kinds. Registered names are the seven short names in that spec. Public names are collision-resistant names, such as a URI you control. Private names are names that are neither registered nor public. A producer and a consumer may agree to use a private name, and that name can collide with someone else’s.

None of the registered claims is mandatory. The JWT spec leaves it to the application to say which ones it requires.

  • iss identifies the issuer. It is a case-sensitive string.
  • sub identifies the subject. The value must be unique in the issuer’s context, or unique globally.
  • aud identifies the intended recipients. One audience may be a string. More than one is an array of strings. If aud is present and the receiver does not find itself in that claim, the receiver must reject the token.
  • exp is the expiration time, a NumericDate. The receiver must not accept the token at that time or after it. Implementers may allow a small leeway, usually no more than a few minutes, for clock skew.
  • nbf is the not-before time, a NumericDate. The receiver must not accept the token before that time.
  • iat is the issued-at time, a NumericDate.
  • jti is a unique id for this token. The spec says it can be used to prevent the token from being replayed.

A NumericDate is seconds since 1970-01-01T00:00:00Z UTC, ignoring leap seconds.

name in the sample payload is a private claim. Because the payload is only encoded, every claim is visible to anyone who copies the token. Leave passwords and other secrets out of it. RFC 7519 says that if the token does contain privacy-sensitive information, send it with a protocol that encrypts the channel and authenticates the endpoint, such as TLS, or encrypt the JWT itself.

Signature

For HS256, the signature is an HMAC-SHA-256 over the JWS Signing Input. That input is the ASCII string formed by the base64url header, a ., and the base64url payload. The HMAC key is the shared secret. The MAC bytes are base64url-encoded and placed after a second ..

The receiver computes that HMAC again and compares it to the signature in the token. RFC 7518 requires the comparison to be done in constant time. A match means those header and payload bytes are the bytes that were signed with that secret. It does not by itself mean the claims are true. Trust depends on who controls the key.

Edit the payload and the old signature no longer matches. jsonwebtoken 9 then throws JsonWebTokenError with the message invalid signature.

How to generate a JWT token

JSON.stringify on the objects below emits the compact JSON used for the sample token. Node’s Buffer encoding base64url produces the segments, and crypto.createHmac produces the signature.

const crypto = require("crypto");

const header = Buffer.from(
  JSON.stringify({ alg: "HS256", typ: "JWT" })
).toString("base64url");
const payload = Buffer.from(
  JSON.stringify({ sub: "1234567890", name: "John Doe", iat: 1516239022 })
).toString("base64url");
const signingInput = `${header}.${payload}`;
const signature = crypto
  .createHmac("sha256", "your-256-bit-secret")
  .update(signingInput)
  .digest("base64url");
const token = `${signingInput}.${signature}`;

header is eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. payload is eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ. signature is SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c. Joining them with dots gives the token in the previous section.

your-256-bit-secret is 19 bytes, which is 152 bits. RFC 7518 says an HS256 key must be 256 bits or larger. The short string is only here so the output matches this sample. A real HMAC key should be at least 32 random bytes.

The jsonwebtoken package on npm builds the same three-part string. This is version 9.0.3:

const crypto = require("crypto");
const jwt = require("jsonwebtoken");

const secret = crypto.randomBytes(32);
const token = jwt.sign(
  { sub: "user-42", role: "member" },
  secret,
  { expiresIn: "15m", issuer: "https://example.com", jwtid: "abc" }
);

algorithm is omitted, so the library uses its default, HS256. The header is {"alg":"HS256","typ":"JWT"}. The payload keeps sub and role. issuer is written as iss, and jwtid is written as jti. The library sets iat to the current time in seconds unless you pass noTimestamp. expiresIn: "15m" sets exp to 900 seconds after iat. There is no default for expiresIn. Leave it out and the payload has no exp, so the token does not expire on its own. If the payload object already has exp, passing expiresIn throws Bad "options.expiresIn" option the payload already has an "exp" property.

RSA signing uses a private key and algorithm: "RS256". RFC 7518 requires a key of 2048 bits or larger for RS256.

const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
  modulusLength: 2048,
});
const token = jwt.sign({ sub: "user-42" }, privateKey, {
  algorithm: "RS256",
});
const claims = jwt.verify(token, publicKey, { algorithms: ["RS256"] });

The header alg is RS256. claims.sub is "user-42". jwt.verify checks the signature with the public key. The private key stays with the signer.

HS256 vs RS256

HS256, HS384, and HS512 are HMAC with SHA-256, SHA-384, and SHA-512. The same secret signs and verifies. That fits when one party does both jobs. Any holder of the secret can also create tokens. The key must be at least as long as the hash output: 256 bits for HS256, 384 bits for HS384, and 512 bits for HS512. RFC 8725 says a human-memorable password must not be used directly as the key for a MAC algorithm such as HS256.

RS256, RS384, and RS512 are RSASSA-PKCS1-v1_5 with SHA-256, SHA-384, and SHA-512. The private key signs. The matching public key verifies. The modulus must be 2048 bits or larger. Other services can hold only the public key. One way to publish it is a JWK Set, the JSON object from RFC 7517 whose keys member is an array of keys. kid on the token selects which member was used.

ES256 is ECDSA using P-256 and SHA-256. ES384 uses P-384 and SHA-384. ES512 uses P-521 and SHA-512. RFC 7518 describes ECDSA as giving equivalent security to RSA with shorter keys, and as faster for many operations. An ES256 signature is 64 octets: R and S, 32 octets each, concatenated.

alg of none means an unsecured JWS. The signature value is the empty octet sequence, so the third part of the compact token is empty. RFC 7518 says implementations must not accept that by default, and must accept it only when the application has said that this object does not need integrity protection. RFC 8725 adds that none is for the case where something else, such as TLS, already protects the token, and that libraries should not create or accept none unless the caller asked for it.

The alg header is not a fact you can trust from the token alone. RFC 8725 describes two failures. One is an attacker changing alg to none so a library skips the signature. The other is changing RS256 to HS256 and MACing the token with the RSA public key, which is public. A verifier that honors alg from the header and uses that public key as the HMAC secret accepts the attacker’s token. The same RFC says a library must let the caller name the allowed algorithms, and each key must be used with exactly one algorithm.

jsonwebtoken 9 follows that split when you pass algorithms. jwt.verify throws JsonWebTokenError with the message invalid algorithm when the header alg is not in that list. jwt.verify also throws secretOrPublicKey must be a symmetric key when using HS256 when the key is a PEM public key and HS256 is the allowed algorithm, so an HMAC made with that PEM is not accepted.

Secret management

Keep the HMAC secret and the RSA private key out of the repository. Load them from the process environment or from a secrets manager when the process starts. Draw an HMAC key from a cryptographic random generator, at least 32 bytes for HS256. Generate RSA keys at 2048 bits or more, or use a P-256 private key when you sign with ES256.

kid exists so a signer can signal a key change. Sign new tokens with the new key, set kid to that key’s id, and keep the previous verification key until tokens signed with it are past exp. In jsonwebtoken 9 the option is keyid, and it is copied to the header as kid. Use a different key in each environment so a token from one environment does not verify in another.

Troubleshooting common JWT errors

The messages below are from jsonwebtoken 9.0.3. Other libraries report the same failures with different text.

  • invalid signature means the MAC or signature does not match this key. Either the key is wrong, or the header or payload changed after signing.
  • jwt expired means the current time is at exp or after it. The error name is TokenExpiredError. A verifier clock that is ahead of the issuer produces this on a token that the issuer still considers fresh. clockTolerance adds leeway in seconds. A token whose exp is 30 seconds in the past fails with the default, and jwt.verify accepts it when clockTolerance is 60.
  • jwt not active means the current time is before nbf. The error name is NotBeforeError.
  • jwt malformed means the string is not a compact token. not-a-jwt throws it, and so does a string with only two segments.
  • invalid algorithm means the header alg is outside the algorithms array passed to jwt.verify.

Read those errors before you trust a claim. Base64url-decoding the middle segment only shows the JSON the signer put there.

JWT libraries

Node’s jsonwebtoken package signs with jwt.sign(payload, secretOrPrivateKey, options). Python’s PyJWT signs with jwt.encode(payload, key, algorithm="HS256"). PHP’s firebase/php-jwt signs with JWT::encode($payload, $key, 'HS256'). Go’s module github.com/golang-jwt/jwt/v5 builds a token with jwt.NewWithClaims and returns the compact string from SignedString. Java’s jjwt, group io.jsonwebtoken, starts at Jwts.builder(). In the 0.12 API, signWith(key) picks the algorithm from the key and compact() returns the string. A 256-bit HMAC SecretKey is signed as HS256.

A page that decodes tokens in the browser can show the header and payload of the sample above, since that HMAC secret is printed in the sample. Do not type a production key, or a real user’s claims, into a website you do not control.

If this article was helpful, tweet it!