- Technicalpig
- Posts
- TechnicalPigđ·: JWTs
TechnicalPigđ·: JWTs
JSON Web Tokens for Security
JWTs (JSON Web Tokens) are a compact, URL-safe means of representing claims between 2 parties. The claims in a JWT are encoded as a JSON object, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.
JWTs are composed of three parts, separated by dots (.
), which are:
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 or RSA.
Payload: 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 claims.
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.
How to use JWTs
Authentication: After the user logs in using their credentials, a JWT is returned and must be saved locally (typically in local storage, but cookies can also be used). With every subsequent request to the server, the JWT is sent in the Authorization header using the Bearer schema. The server then validates the token and, if itâs valid, returns the requested resource. Since JWTs are self-contained, they reduce the need for the server to query the database more than once upon authentication, thus making it useful for scaling applications.
Information Exchange: JWTs are a good way of securely transmitting information between parties. Because JWTs can be signedâfor example, using public/private key pairsâyou can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.
How to implement JWTs
Step 1: Install a JWT library depending on your programming language. For example, for Node.js you might use jsonwebtoken
, for Python PyJWT
, and for Java java-jwt
.
Step 2: Create JWTs on the server after user authentication, including any claims relevant to your application in the payload.
Step 3: Sign the JWT using a secret or a private key. The server must keep this secret or private key secure at all times.
Step 4: Send the JWT to the client, which will store it and include it in the Authorisation header in subsequent requests.
Step 5: Validate the JWT on the server on every request. Check the signature and any claims that dictate what the user can access to ensure they are allowed to perform the action they are requesting.
Step 6: Manage JWT expiration. JWTs should have an expiration claim, after which they are no longer valid. Your application needs to handle expired tokens, usually prompting the user to log in again or refreshing the token automatically if refresh tokens are implemented.
How does Validation work
First, the server retrieves the JWT from incoming requests, usually form the Authorisation header.
The server then decodes the JWT by breaking it down into 3 parts - the header, payload and signature.
The most crucial step is to validate the JWT to ensure that the token was indeed issued by a trusted issuer and hasnât been tampered with.
For HS256 (HMAC + SHA256): The server uses the same secret key that was used to sign the token to generate a new Base64-url-encoded signature from the header and payload. It then compares this signature with the one in the token. If they match, the token is considered valid.
For RS256 (RSA Signature with SHA-256): The server uses the public key corresponding to the private key that signed the token to verify the signature. If the signature is valid, the token is considered to have been signed by the corresponding private key and is thus valid.
After verifying the signature, the server checks the payload or the claims of the token such as whether the token has expired.
If all checks pass, the server considers the JWT valid and the request can proceed.