JWT
- tags
- Security
Acronym #
JSON Web Token
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained method for securely transmitting information between parties encoded as a JSON object. JWT has gained mass popularity due to its compact size which allows tokens to be easily transmitted via query strings, header attributes and within the body of a POST request.
Structure #
Header #
- Contains the type of the token (JWT) and the signing algorithm used (e.g., HS256, RSA).
- Encoded in base64 format.
- Example: “alg”: “HS256”, “typ”: “JWT”
Payload #
- Contains Claim which are statements about an entity (typically the user) and additional data.
- Types of claims:
- Registered Claims: Predefined claims recommended for interoperability (e.g., iss, exp, sub, aud).
- Public Claims: Custom claims to share information between parties.
- Private Claims: Custom claims used to share information between parties that have agreed on using them.
- Also encoded in base64 format.
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.
- Created by taking the encoded header, the encoded payload, a secret, the algorithm specified in the header, and signing it.
- Ensures the integrity of the data.
Why Use Tokens? #
The use of tokens has many benefits compared to traditional methods such as cookies.
Tokens are stateless. The token is self-contained and contains all the information it needs for authentication.
This is great for scalability as it frees your server from having to store session state.Tokens can be generated from anywhere. Token generation is decoupled from token verification allowing you the option to handle the signing of tokens on a separate server or even through a different company such us Auth0.
Fine-grained access control. Within the token payload you can easily specify user roles and permissions as well as resources that the user can access.
These are just some of the benefits JSON Web Tokens provide. To learn more check out this blog post that takes a deeper dive and compares tokens to cookies for managing authentication.
Anatomy of a JSON Web Token #
