Junior
What is JWT (JSON Web Token)?
sobes.tech AI
Answer from AI
JSON Web Token (JWT) is a compact, URL-safe way to transmit data between parties in JSON format.
Working principles:
- The token consists of three parts separated by dots (
.):header.payload.signature. - Header: Contains metadata about the token, such as token type (JWT) and the signature algorithm used (e.g., HS256, RS256).
{
"alg": "HS256",
"typ": "JWT"
}
- Payload: Contains "claims" - assertions or information we want to transmit. There are several types:
- Registered claims: Reserved but optional claims, such as
iss(issuer),exp(expiration),sub(subject). - Public claims: Defined for public use, should be registered in the IANA JSON Web Token Registry or be URIs containing a namespace, protected from collisions.
- Private claims: Arbitrary assertions agreed upon between parties.
- Registered claims: Reserved but optional claims, such as
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
- Signature: Created by combining the encoded header and payload with a secret and the algorithm specified in the header. This ensures token integrity — if someone alters the header or payload, the signature will be invalid.
# Example of creating a signature using HS256
import hmac, hashlib
header_str = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' # Base64Url(Header)
payload_str = 'eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ' # Base64Url(Payload)
secret = 'your_secret_key'
# Signature = HMACSHA256(Base64Url(Header) + "." + Base64Url(Payload), secret)
signature = hmac.new(
secret.encode('utf-8'),
(header_str + '.' + payload_str).encode('utf-8'),
hashlib.sha256
).digest()
# Encode signature in Base64Url
import base64
signature_b64url = base64.urlsafe_b64encode(signature).rstrip(b'=').decode('ascii')
# Final token: header_str + '.' + payload_str + '.' + signature_b64url
Applications:
- Authorization: The server issues a token to the user after successful authentication. The user sends this token with each request. The server verifies the token's validity and grants access to resources.
- Data exchange: Secure transmission of small data volumes between different services.
Advantages:
- Compactness: Less data to transmit compared to XML.
- Self-contained: The token already contains necessary user information, reducing the need to access the database on each request.
- Stateless: The server does not need to store session information.
- Cryptographic signature: Ensures data integrity.
Disadvantages:
- Token revocation impossible: Once issued, the token remains valid until expiration unless a blacklist mechanism is implemented.
- Secret storage: The secret key must be stored securely.
- Size: The size of the token increases with the amount of data in the
payload.