What is JWT?
Official Site Definition: JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
Although JWTs can be encrypted to also provide secrecy between parties, we will focus on signed tokens. Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.
Confused Right? Let's break it down.
Let's break it down into simpler terms
JSON Web Tokens (JWT) are like digital passports for the web. They contain information (like your name or email) that websites use to know who you are and what you can do. Here's why they're useful:
No Need to Keep Asking: Once you log in, the website gives you a JWT. You can show this JWT whenever you need to do something on the website, so the website doesn't have to keep asking for your username and password.
Small and Fast: JWTs are small files, so they travel quickly over the internet. This makes websites faster because they don't have to send big files back and forth.
Keeps Your Information Safe: JWTs are like secret codes. Only the website knows how to read them, so your information stays safe.
Works Everywhere: JWTs work on any website, making them great for different parts of the internet to talk to each other securely.
Easy for Developers: Developers like using JWTs because they're simple to use and make websites more secure and faster.
Structure of JWT
A JWT consists of three parts separated by periods (.), which are base64url-encoded strings:
- Header: The header generally comprises two components - the token type (JWT) and the signing algorithm in use, like HMAC SHA256 or RSA.
Example:
{
"alg": "HS256",
"typ": "JWT"
}
- Payload: The payload holds the claims, which are statements about the user or other data. Claims can be of three types: registered, public, and private claims.
Example:
{
"account": "user123",
"name": "Dhiraj Beri"
}
3. Signature: To create the signature part, you need to take the encoded header, encoded payload, a secret, and the algorithm specified in the header, then sign that with the secret. The signature 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.
Example (using HMAC SHA256):
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
- Here on the left side is the JWT token. Anyone can decode its values. On the right side, we have the header, payload, and the verification signature.
Advantages of JWT
Stateless: Since JWTs carry all the necessary information within themselves, the server doesn’t need to maintain session information. This makes JWTs stateless, which reduces server load and simplifies scalability.
Compact and Efficient: Due to their compact size, JWTs are suitable for transmission over networks and are easily parsed by clients.
Security: JWTs are digitally signed, ensuring data integrity and preventing tampering. Using encryption algorithms enhances the security further.
Cross-Domain Communication: JWTs can be used across different domains or micro-services since they don’t rely on cookies or server-side sessions.
Best Practices for JWT Implementation
Secure Storage: Store JWTs in HTTP-only cookies to prevent access from JavaScript, reducing the risk of XSS attacks.
Token Expiration: Set a reasonable expiration time on JWTs to limit the time window for potential misuse.
Token Revocation: Have a mechanism to revoke or blacklist compromised tokens to enhance security.
Use HTTPS: Ensure that all communications between the client and server use HTTPS to prevent eavesdropping and man-in-the-middle attacks.
Don’t Store Sensitive Data: Avoid storing sensitive data in the JWT payload, as the payload is easily readable once decoded.
Below is a sample code for JWT implementation in a Node.js application using the jsonwebtoken
library, which is a popular library for generating and verifying JWTs.
Generate
Decode
Verify
Generating a JWT
To generate a JWT, you can use the sign
method from the jsonwebtoken
library. This method takes a value (payload) and a secret key and returns a JWT.
const jwt = require("jsonwebtoken");
const payload = {
name: "Dhiraj",
account: 123456789,
};
const secretKey = "secret";
const token = jwt.sign(payload, secretKey);
console.log(token);
Decoding a JWT
Decoding a JWT involves extracting the payload from the token. This can be done by anyone, as decoding does not require the secret key. However, decoding only reveals the contents of the token and does not verify its authenticity.
const decoded = jwt.decode(token);
console.log(decoded);
Verifying a JWT
Verifying a JWT involves ensuring that the token is authentic and has not been tampered with. This requires the secret key used to generate the token. Only the backend server should have access to this key, ensuring that only the server can verify the token's authenticity.
try {
const verified = jwt.verify(token, secretKey);
console.log(verified);
} catch (err) {
console.error("Invalid token");
}
Conclusion
In conclusion, JSON Web Tokens (JWT) provide a secure and efficient way to transmit information between parties. They are widely used for authentication and data exchange in web development. By understanding how to generate, decode, and verify JWTs, developers can ensure the security and integrity of their applications.