JSON Web Tokens (JWT) are a compact, URL-safe means of representing claims to be transferred between two parties. Here's an example of a JWT and a breakdown of its components.
A JWT consists of three parts: the header, the payload, and the signature. These parts are encoded as Base64Url strings and separated by dots (.
). Here is an example of a JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
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 or RSA.
Example header:
{ "alg": "HS256", "typ": "JWT" }
When Base64Url encoded, this header becomes:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
The payload 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.
Example payload:
{ "sub": "1234567890", "name": "John Doe", "iat": 1516239022 }
sub
(subject): Identifier for the user.name
: Name of the user.1iat
(issued at): Timestamp when the token was issued.When Base64Url encoded, this payload becomes:
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
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.
For example, if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
Given the secret your-256-bit-secret
, the signature is generated as follows:
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Combining these three encoded parts results in the JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
To verify the JWT, the recipient must:
JWTs are used extensively in web applications for authentication and information exchange because of their compactness and security features when properly signed and verified.