What is JWT?
JWT stands for JSON Web Token. It is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.
Key Features of JWT:
- Compact: JWTs are small in size, making them ideal for use in HTTP headers, URL parameters, or cookies.
- Self-Contained: They contain all the necessary information about the user, which reduces the need for repeated database queries.
- Secure: JWTs can be signed and/or encrypted to ensure the integrity and confidentiality of the information.
Structure of a JWT:
A JSON Web Token is comprised of three parts:
- Header:
Typically consists of two parts:
- Type: Usually “JWT”.
- Algorithm: The signing algorithm being used (e.g., HMAC SHA256, RSA).
Payload:
- Contains the claims. Claims are statements about an entity (typically, the user) and additional data.
There are three types of claims:
- Registered: Predefined claims such as
iss
(issuer),exp
(expiration time), etc. - Public: Custom claims that can be defined by the developer.
- Private: Custom claims that are used within a specific context.
- Registered: Predefined claims such as
Signature:
- The signature is created by combining the encoded header, encoded payload, and a secret key.
- This ensures that the sender is who it claims to be and that the message wasn’t changed along the way.
Example of a JWT:
A typical JWT looks like this:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
- Header Base64:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
- Payload Base64:
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
- Signature:
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Common Use Cases for JWT:
- Authentication: Verifying the identity of users upon login.
- Information Exchange: Securely transmitting information between parties.
- Single Sign-On (SSO): Allowing users to authenticate across multiple applications with a single login.
Conclusion
JWTs are a powerful tool for modern web applications, providing a secure, efficient, and compact means of transmitting information. Understanding their structure and use cases is essential for developers working with authentication and data exchange in their applications.