ThisCalculator

Everyday

JWT Token Generation: Claims, Keys, and Libraries

Updated · Standard formula, shown below

The calculator for this page is switched off while it is checked. The formula is below, and the worked example in the article shows how to use it by hand.

JWT Token Generation: Claims, Keys, and Libraries

JWT token generation works by signing a header and a payload (claims) with a secret key or a public/private key pair, using a library that implements the JWT standard. You provide the claims (like subject, issuer, expiration), choose a signing algorithm, and the library outputs a compact, URL-safe string. This article explains the core concepts, how to choose a library, and common pitfalls.

Formula

The JWT itself is not computed by a single formula, but the expiration time is: exp = iat + ttl, where exp is the expiration timestamp (Unix epoch seconds), iat is the issued-at timestamp (Unix epoch seconds), and ttl is the time-to-live in seconds. The secret entropy is roughly entropy = length × 6 bits for a random base64-encoded secret (each character carries about 6 bits of entropy).

Worked Example

Using the defaults: t = 60 minutes, s = 32 characters.

  1. Convert minutes to seconds: 60 × 60 = 3600 seconds.
  2. If the current time is 1700000000 (Unix epoch), then exp = 1700000000 + 3600 = 1700003600.
  3. Secret entropy: 32 × 6 = 192 bits.

The calculator shows exp = 3600 (the offset from now) and entropy = 192 bits. In practice, the library adds the current time to the offset.

What Is a JWT?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact, URL-safe way to transmit claims between parties. A JWT consists of three parts: a header, a payload, and a signature. The header typically specifies the signing algorithm (e.g., HS256 or RS256). The payload contains the claims – statements about the user and metadata. The signature is computed over the header and payload using a secret key (HMAC) or a private key (RSA/ECDSA).

JWTs are commonly used for authentication (ID tokens) and authorization (access tokens). They are self-contained, meaning the receiving party can verify the token without querying a database, as long as it has the key.

Claims: The Core of a JWT

Claims are key-value pairs in the payload. There are three types:

  • Registered claims: Predefined, optional claims like iss (issuer), sub (subject), aud (audience), exp (expiration), nbf (not before), iat (issued at), and jti (JWT ID).
  • Public claims: Custom claims defined by you, but should be collision-resistant (e.g., using a URI or a namespaced name).
  • Private claims: Custom claims agreed upon between the parties, not meant to be public.

When generating a token, you decide which claims to include. At minimum, you should include exp to prevent tokens from living forever. The sub claim usually identifies the user. The aud claim restricts which server can accept the token.

Keys: Symmetric vs. Asymmetric

The signing key is what makes a JWT secure. There are two main categories:

  • Symmetric (HS256, HS384, HS512): The same secret key is used to sign and verify. This is fast and simple, but the key must be kept secret and shared between parties. Suitable for a single server or trusted services.
  • Asymmetric (RS256, ES256, etc.): A private key signs, and a public key verifies. The private key stays with the issuer; the public key can be distributed. This allows multiple parties to verify without sharing secrets. RS256 is common for OAuth providers.

Key length matters. For HS256, use a secret of at least 256 bits (32 bytes). For RS256, use at least 2048-bit RSA keys. Many libraries provide key generation utilities.

How to Choose a JWT Library

Most programming languages have mature JWT libraries. When choosing, consider:

  • Language support: Pick a library that is actively maintained and widely used in your ecosystem (e.g., jsonwebtoken for Node.js, PyJWT for Python, java-jwt for Java).
  • Algorithm support: Ensure it supports the algorithms you need (HS256, RS256, etc.).
  • Security features: Look for protection against algorithm confusion (e.g., rejecting tokens with alg: none).
  • Documentation and community: A well-documented library with examples reduces mistakes.

For most applications, a well-known library is better than writing your own. Implementing JWT from scratch is error-prone and can lead to vulnerabilities.

Common Mistakes and Misconceptions

Here are frequent pitfalls when generating JWTs:

  • Using a weak secret: A short or predictable secret can be brute-forced. Use a cryptographically random string of at least 32 characters.
  • Not setting expiration: Tokens without exp are valid forever. Always set a reasonable TTL.
  • Storing sensitive data in claims: The payload is base64-encoded, not encrypted. Anyone can decode it. Do not put passwords or personal data.
  • Ignoring the audience: If you don’t check aud, a token issued for one service might be accepted by another.
  • Algorithm confusion attacks: Some libraries allow you to specify the algorithm in the header. An attacker could switch from RS256 to HS256 and sign with the public key. Modern libraries mitigate this by fixing the algorithm.

A common misconception is that JWTs are encrypted. They are not – they are signed. The content is visible to anyone who decodes the base64url. If you need confidentiality, use JWE (JSON Web Encryption) or a separate encryption layer.

Comparing JWT to Alternatives

JWT is not the only way to handle tokens. Here is a quick comparison:

  • Opaque tokens: Random strings stored in a database. They are revocable and simple, but require a database lookup on each request.
  • Sessions: Server-side state with a cookie. Easy to revoke, but not stateless and can be hard to scale.
  • PASETO: A newer standard that aims to be simpler and more secure than JWT, avoiding some of JWT’s flexibility that leads to mistakes.

JWT is stateless and works well for distributed systems, but revocation is hard because tokens are valid until they expire. If you need immediate revocation, opaque tokens or a token blacklist are better.

Frequently Asked Questions

What is the difference between JWT and JWS?

JWS (JSON Web Signature) is the underlying standard for the signature part of a JWT. A JWT can be a JWS (signed) or a JWE (encrypted). In practice, when people say JWT, they usually mean a signed JWS token.

Can I decode a JWT without the key?

Yes, the header and payload are base64url-encoded, not encrypted. You can decode them with any base64 decoder. The signature cannot be verified without the key, but the content is readable.

How long should a JWT be valid?

It depends on your use case. For access tokens, 15 minutes to 1 hour is common. For refresh tokens, days or weeks. Shorter is safer because it limits the window of misuse if a token is stolen.

What is the best algorithm for JWT signing?

For most server-to-server scenarios, HS256 with a strong secret is fine. For public/private key scenarios (like OAuth), RS256 is widely used. ES256 (ECDSA) is faster and uses smaller keys, but requires careful random number generation.

How do I rotate JWT signing keys?

Generate a new key and add it to your verification set, while keeping the old key for a transition period. Sign new tokens with the new key, but accept tokens signed with the old key until they expire. Then remove the old key.

Is it safe to put user ID in the JWT?

Yes, as long as the token is signed and the user ID is not sensitive. The user ID is visible, but cannot be tampered with because the signature would fail. Avoid putting email addresses or other personal data in the payload.

Related

Formula used
in t | Expiration (minutes) | min | 60 | 0
in s | Secret length (chars) | chars | 32 | 16
out exp | Expiration (epoch) | s | t * 60 | 0
out entropy | Secret entropy (bits) | bits | s * 6 | 0

Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.