A JSON Web Token (JWT) is a compact, URL-safe means of representing claims that can 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.
Here’s how JWT works internally:
The client sends a request to the server to authenticate a user.
The server verifies the user’s credentials and generates a JWT if the user is authenticated.
The server sends the JWT back to the client.
The client stores the JWT and includes it in the header of subsequent requests to protected routes on the server.
The server verifies the JWT and processes the request if the token is valid.
A JWT consists of three parts: a header, a payload, and a signature.
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.
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.
The third part of the token is the signature, which is used to verify that the sender of the JWT is who it says it is and to ensure that the message wasn’t changed along the way.
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)
The complete JWT is then composed by concatenating the encoded header, the encoded payload, and the signature, with periods (.) separating them. For example:
xxxxx.yyyyy.zzzzz