What is JWT?
JSON Web Token (JWT) 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.
A JWT typically consists of three parts:
- Header: Contains metadata about the token, such as the type of token (JWT) and the signing algorithm used, e.g., HMAC, SHA256 or RSA.
{ "alg": "HS256", "typ": "JWT" }When Base64Url encoded, this header looks like:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
- Payload: Contains the claims, which are statements about an entity (typically, the user) and additional data. There are three types of claims:
- Registered claims: Predefined claims that are not mandatory but recommended, such as
iss(issuer),exp(expiration time),sub(subject), andaud(audience). - Public claims: Custom claims that can be defined to share information.
- Private claims: Custom claims created to share information between parties that agree on using them.
{ "iss": "your-issuer", "exp": 1716239022, "sub": "1234567890", "aud": "your-audience", "name": "Ravishanker", "admin": true, "iat": 1516239022 }When Base64Url encoded, this payload looks like:
eyJpc3MiOiJ5b3VyLWlzc3VlciIsImV4cCI6MTcxNjIzOTAyMiwic3ViIjoiMTIzNDU2Nzg5MCIsImF1ZCI6InlvdXItYXVkaWVuY2UiLCJuYW1lIjoiUmF2aXNoYW5rZXIiLCJhZG1pbiI6dHJ1ZSwiaWF0IjoxNTE2MjM5MDIyfQ
- Registered claims: Predefined claims that are not mandatory but recommended, such as
- Signature: 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.
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), your-256-bit-secret)
Resulting signature might look like:
dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
A JWT is represented as a sequence of Base64Url encoded strings separated by dots (.), e.g., header.payload.signature. Putting all these together, the updated JWT would look like:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJ5b3VyLWlzc3VlciIsImV4cCI6MTcxNjIzOTAyMiwic3ViIjoiMTIzNDU2Nzg5MCIsImF1ZCI6InlvdXItYXVkaWVuY2UiLCJuYW1lIjoiUmF2aXNoYW5rZXIiLCJhZG1pbiI6dHJ1ZSwiaWF0IjoxNTE2MjM5MDIyfQ.dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk
Pros & Cons of JWT
Pros of JSON Web Tokens (JWT)
- Stateless Authentication: JWTs are stateless, meaning the server does not need to store session information. This reduces server load and allows for horizontal scaling.
- Compact and URL-Safe: JWTs are compact and can be easily transmitted via URL parameters, headers, or cookies. They are Base64Url encoded, making them safe for inclusion in URLs.
- Cross-Domain and Mobile-Friendly: JWTs are well-suited for cross-domain authentication and mobile applications because they can be transmitted easily and securely across different services and devices.
- Decentralized Verification: Any server with the public key can verify the token, enabling decentralized authentication across multiple services without a central session store.
- Customizable Claims: JWTs allow the inclusion of custom claims, enabling flexible and rich representations of user information and session data
Cons of JSON Web Tokens (JWT)
- Token Revocation Challenges: Revoking a JWT before its expiration time is challenging because the token is stateless and does not reside on the server. Implementing revocation lists or other mechanisms adds complexity.
- Security Risks: JWTs are vulnerable to specific attacks if not properly implemented, such as none algorithm attacks or key confusion attacks.
- Token Size: JWTs can become large if they contain many claims, potentially impacting performance and storage, especially if included in every request header.
Common JWT Attacks
JWTs can be subject to various types of attacks if not properly implemented:
- None Algorithm Attack: If the server supports the
nonealgorithm for verification, an attacker can craft a token with thenonealgorithm and bypass the signature verification process. - Key Confusion Attack: If a server does not properly differentiate between symmetric and asymmetric keys, an attacker can exploit this by substituting the
algclaim to trick the server into using the wrong type of key. - Brute Force Attacks: If the signing key is weak or improperly managed, attackers can use brute force methods to discover the key and forge valid tokens.
- Replay Attacks: Without proper mechanisms like nonce or timestamp validation, an attacker can capture a valid token and reuse it to gain unauthorized access.
Best Practices for JWT
To ensure the security of JWTs, follow these best practices:
- Use Strong Algorithms: Always use strong signing algorithms such as RS256 or ES256. Avoid using the
nonealgorithm or weak algorithms like HS256 with weak keys. - Validate Claims: Always validate important claims such as
iss,aud,exp, andnbf. Ensure that the token is intended for your application, issued by a trusted source, and within its validity period. - Secure Key Management: Use secure methods to generate, store, and rotate keys. Keep keys confidential and use environment variables or secret management services for storing keys.
- Short Expiry Times: Set short expiration times for tokens to limit the window of opportunity for attackers in case of token compromise. Refresh tokens can be used to obtain new access tokens without requiring re-authentication.
- Secure Storage and Transmission: Store tokens securely on the client side, using secure, HTTP-only cookies. Ensure that tokens are always transmitted over HTTPS to prevent interception.
- Implement Token Revocation: Implement mechanisms to revoke tokens when necessary. This can include maintaining a blacklist of tokens or using a centralized token management system.
- Monitor and Log Usage: Monitor and log token usage to detect abnormal patterns and potential security incidents. Implement rate limiting to protect against brute force and replay attacks.
- Use Libraries and Standards: Use well-maintained libraries and adhere to established standards for JWT implementation. Regularly update libraries to incorporate the latest security patches and best practices.
By following these best practices and being aware of potential vulnerabilities, you can effectively utilize JWTs in a secure and robust manner, ensuring the integrity and confidentiality of your application’s authentication and authorization processes.
