JWT, or JSON Web Tokens (Part-1)

JWT, or JSON Web Tokens (Part-1)

Demystifying JWTs: Understanding JSON Web Tokens

In today's blog post, we've discussed essential aspects of JSON Web Tokens (JWTs), including Claims, Signature, and the advantages of JWTs being both Stateless and Scalable.

JWTs are secure, self-contained methods used for authentication and authorization in web applications and APIs. They consist of a header, payload, and signature, with the header defining the token type and the signature ensuring its integrity. This stateless approach is scalable and efficient, eliminating the need for server storage.

JWT (JSON Web Tokens) and its key applications.

  • Claims

  • Signature

  • Stateless and Scalable

  • Use Cases

  • Security Considerations

  • Token Expiration

Claims

A JWT payload contains claims, statements about an entity and data, with three types: registered, public, and private. Registered claims are predefined, public claims are defined, and private claims are custom.

  • Registered Claims

  • Public Claims

  • Private Claims

Registered Claims

  • 'iss' (Issuer): This field represents the entity that issued the JWT.

  • 'sub' (Subject): Identifies the JWT's subject (often the user).

  • 'exp' (Expiration Time): Specifies the token's expiration date.

  • 'nbf' (Not Before): This specifies the time after which the token must not be acknowledged.

  • 'iat' (Issued At): Indicates when the token was issued.

  • 'aud' (Audience): Identifies the receivers who will get the JWT.

{
  "iss": "example.com",
  "sub": "1234567890",
  "exp": 1617319700,
  "iat": 1617316100,
  "aud": "myapp"
}

Public Claims

The JWT standard defines public claims, but they may also be used to share public information. They are not restricted to a single application or company.

  • name: The user's name.

  • email: The user's email address.

  • role: The user's role or permissions.

  • locale: The desired language or locale of the user.

{
  "name": "John Doe",
  "email": "johndoe@example.com",
  "role": "user",
  "locale": "en-US"
}

Private Claims

Private claims are bespoke claims generated to exchange information between parties that have agreed to use them. These claims are not standardized, and the parties concerned should define and record them.

{
  "company_id": 12345,
  "employee_id": "E56789",
  "custom_data": "some custom value"
}

In the case of private claims, "company_id" and "employee_id" are unique to the parties involved and reflect bespoke data pertinent to their use case. Any additional data required for their application can be included in the "custom_data" claim.

Signature

The signature in a JWT is crucial for its authenticity and integrity, generated using a header, payload, and secret key, which can be verified by the recipient.

A particular algorithm and a secret key are used to produce and validate the signature in a JWT. Here's an example of how to produce and validate a JWT signature in Python using the PyJWT package, which is widely used for working with JWTs

Generating a JWT with a Signature

import jwt

# Define the payload (claims) and the secret key
payload = {"user_id": 123, "username": "exampleuser"}
secret_key = "your_secret_key"

# Create a JWT with a signature
token = jwt.encode(payload, secret_key, algorithm="HS256")

# The 'token' now contains the JWT with a signature
print(token)

we create a JWT with a payload (claims) and a secret key using the HMAC SHA-256 (HS256) algorithm.

Verifying a JWT Signature

import jwt

# The JWT received from the client
received_token = "your_received_token_here"

# The secret key used for verification
secret_key = "your_secret_key"

try:
    # Verify the JWT's signature
    payload = jwt.decode(received_token, secret_key, algorithms=["HS256"])
    print("Token is valid")
    print("Payload:", payload)
except jwt.ExpiredSignatureError:
    print("Token has expired")
except jwt.InvalidTokenError:
    print("Token is invalid")

The example involves verifying a client's JWT signature using a secret key, extracting the payload, and ensuring the secret key is kept confidential. The algorithm used should match the generation and verification steps, raising exceptions.

Stateless and Scalable

JWTs are stateless, containing all necessary information for server verification, making them easier to scale and more efficient than traditional data storage methods.

Statelessness

Stateless authentication eliminates the need for server storage of session data for authenticated users. Traditional session-based systems store session information, requiring server tracking and managing cookies or database records. JWTs, which contain user claims, store all necessary information, resulting in a lightweight, efficient authentication process.

Scalability

JWTs' statelessness aids the scalability of web applications and APIs in various ways.

  • Load Balancing

  • Reduced Server Overhead

  • Caching

  • Microservices

Load Balancing

Stateless authentication is ideal for load balancing as it eliminates server-side session data, allowing requests to be distributed evenly across multiple servers, and enabling horizontal scaling.

Reduced Server Overhead

Stateless authentication minimizes server overhead by allowing servers to focus on processing requests and responding quickly to clients without managing session data.

Caching

Stateless JWTs can be cached by intermediate layers like CDNs or caching proxies, reducing application server load by serving frequently requested JWTs without application-side processing.

Microservices

JWTs are crucial for authentication and authorization in microservices architectures, where multiple services collaborate to provide a complete application, eliminating the need for centralized session management.

💡
JWTs enhance scalability in web applications by simplifying authentication and reducing session management. However, they require secure use, with secret key protection to prevent tampering or forged tokens.

to be continued ...

Summary
A JWT (JavaScript Web Token) contains claims, statements about an entity and additional data, with three types: registered, public, and private. A signature is crucial for ensuring token integrity and authenticity, generated using a header, payload, and secret key. JWTs are stateless, containing all necessary information for server verification, making them easier to scale and more efficient.

Your engagement and interest in these topics are greatly appreciated. In our next blog post, we will delve into additional important topics, namely Use Cases, Security Considerations, and Token Expiration. These aspects are crucial for a comprehensive understanding of how JWTs can be effectively applied and secured in various applications.

Thank you for your continued interest, and we look forward to sharing more insights in our upcoming blog post.