What is a JWT?
A JSON Web Token (JWT), defined in RFC 7519, is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.
JWT Structure
A typical JWT looks like a long string of seemingly random characters, separated by two periods (`.`). This creates three distinct segments:
header.payload.signature1. The Header
The header typically consists of two parts: the type of the token, which is `JWT`, and the signing algorithm being used, such as HMAC SHA256 (`HS256`) or RSA (`RS256`).
2. The Payload
The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.
- Registered claims: These are a set of predefined claims which are not mandatory but recommended, to provide a set of useful, interoperable claims. Examples include:
iss(issuer),exp(expiration time),sub(subject),aud(audience),nbf(not before), andiat(issued at). - Custom claims: Claims that you define yourself for your specific application domain (e.g.,
role,tenant_id).
3. The Signature
To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
Base64URL Encoding
Notice that the header and payload are encoded, not encrypted. Specifically, they use Base64URL encoding. This ensures that the token is safe to pass through URLs and HTTP headers without characters like + or / causing routing issues.
Security Warning: Decoding ≠ Verification
Because the header and payload are only Base64URL encoded, anyone can decode a JWT and read its contents. You must never put secret information (like passwords) inside a JWT payload. Furthermore, the fact that you can decode a JWT does not mean it is authentic. The only way to trust the data inside a JWT is to cryptographically verify the signature against the server's secret or public key.