JSON Web Tokens - potatoscript/json GitHub Wiki

🎯 JSON Web Tokens (JWT)

JSON Web Tokens (JWT) are a popular method for securely transmitting information between parties in the form of a JSON object. They are widely used in modern web applications for authentication and authorization, especially in RESTful APIs. JWT is compact, URL-safe, and can be used in web applications, mobile applications, and even IoT devices. In this section, we’ll explore what JWT is, how it works, and how you can use it in your applications.


🧩 1. What is JWT?

JWT stands for JSON Web Token, and it is a standard for creating tokens that securely transmit information between two parties. JWTs are often used for authentication and authorization.

A JWT typically contains a header, a payload, and a signature, all encoded in a compact string format. It allows servers and clients to verify the token’s authenticity and ensure the integrity of the data it carries.


1.1 Structure of a JWT

A JWT consists of three parts:

  1. Header: This part contains metadata about the token, including the type of token (JWT) and the signing algorithm used (e.g., HMAC SHA256 or RSA).
  2. Payload: This is where the claims (data) are stored. Claims are statements about an entity (usually, the user) and additional data.
  3. Signature: The signature is used to verify that the sender of the JWT is who it says it is, and to ensure that the message wasn’t altered along the way.

JWT Format:

A JWT is typically represented as three base64-encoded strings, separated by periods (.). For example:

header.payload.signature

🧩 2. JWT Header

The header typically consists of two parts:

  • Type of the token, which is JWT.
  • Signing algorithm, such as HMAC SHA256 or RSA.

Example of JWT Header (JSON):

{
  "alg": "HS256",
  "typ": "JWT"
}

The above header is base64 encoded and forms the first part of the JWT.


🧩 3. JWT Payload

The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. Claims can be divided into three types:

  1. Registered Claims: These are predefined claims that are not mandatory but recommended. Some examples are:

    • iss (issuer)
    • exp (expiration time)
    • sub (subject)
    • aud (audience)
  2. Public Claims: These can be freely defined by anyone, but they should be unique to avoid collision.

  3. Private Claims: These are custom claims created to share information between parties that agree on them.

Example of JWT Payload (JSON):

{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

In this example:

  • sub is a private claim representing the subject (user ID).
  • name is a public claim for the user's name.
  • iat (issued at) is a registered claim that indicates when the token was issued.

The payload is also base64 encoded, forming the second part of the JWT.


🧩 4. JWT Signature

The signature ensures the token’s integrity and authenticity. To create the signature, the following steps are performed:

  1. Take the encoded header and encoded payload.
  2. Combine them with a secret key (using the specified signing algorithm).
  3. Apply the algorithm to get the final signature.

The signature is used to verify the token, ensuring that the sender is who they claim to be and that the message hasn’t been tampered with.

Example of Signature Generation:

  • The signature is created using the algorithm specified in the header, such as HMAC SHA256:
HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload),
  secretKey)

🧩 5. Example of JWT

Here’s an example of a JWT:

eyJhbGciOiAiSFMyNTYiLCJ0eXAiOiAiSlXzV0FSIn0.eyJzdWIiOiAiMTIzNDU2Nzg5MCIsIm5hbWUiOiAiSm9obiBEb2UiLCJpYXQiOiAxNTE2MjM5MDIyfQ.NjM1ZWA1zFPvddahMOewUJNEr6HXB9HeDJ4f1dsMyvS8

This JWT consists of three parts:

  1. Header (base64 encoded)
  2. Payload (base64 encoded)
  3. Signature (generated using the header, payload, and a secret key)

🧩 6. How JWT Works

6.1 Authentication with JWT

JWTs are commonly used for user authentication. Here’s how the process typically works in a web application:

  1. User Login: When a user logs in, they provide their username and password.
  2. Server Validates Credentials: The server checks if the credentials are correct.
  3. JWT is Issued: Once the credentials are validated, the server generates a JWT with user-related claims (e.g., userId, role, etc.) and sends it back to the user.
  4. User Makes Requests: The user sends the JWT with each subsequent HTTP request (usually in the Authorization header).
  5. Server Verifies JWT: On each request, the server verifies the JWT's signature and extracts the payload to identify the user and their permissions.

6.2 Example of Authentication Flow:

  1. Login Request (POST)
    The user submits a login request with their username and password.

    POST /login
    {
      "username": "john_doe",
      "password": "password123"
    }
    
  2. JWT Response
    If the credentials are correct, the server sends a JWT in response.

    HTTP/1.1 200 OK
    {
      "access_token": "eyJhbGciOiAiSFMyNTYiLCJ0eXAiOiAiSlXzV0FSIn0.eyJzdWIiOiAiMTIzNDU2Nzg5MCIsIm5hbWUiOiAiSm9obiBEb2UiLCJpYXQiOiAxNTE2MjM5MDIyfQ.NjM1ZWA1zFPvddahMOewUJNEr6HXB9HeDJ4f1dsMyvS8"
    }
    
  3. Subsequent Requests with JWT The client includes the JWT in the Authorization header for subsequent requests.

    GET /user/profile
    Authorization: Bearer <your_jwt_token>
    

🧩 7. JWT Use Cases

7.1 Authentication

  • The most common use case for JWT is authentication. After login, a server can issue a JWT that the client can use to authenticate subsequent requests.

7.2 Authorization

  • JWT can also be used for authorization. For example, the server may include roles or permissions in the payload (e.g., role: "admin"). This allows the server to authorize users based on the claims in the token.

7.3 Information Exchange

  • Since JWTs are signed, they can also be used to exchange information securely between parties. This information can be verified and trusted because the signature ensures its integrity.

🧩 8. Benefits of JWT

  • Compact: JWTs are small in size, making them efficient to transmit over networks.
  • Self-contained: JWTs contain all the necessary information, so they don’t need to query a database for authentication information.
  • Stateless: JWTs are stateless, meaning the server doesn’t need to maintain session information between requests.
  • Secure: JWTs use signatures to ensure the integrity of the data.

🧩 9. Security Considerations

While JWT is secure, there are several best practices to ensure its safe use:

  • Use HTTPS: Always transmit JWTs over secure connections (HTTPS) to prevent interception.
  • Short Expiry Times: Use short expiration times (exp claim) and refresh tokens to minimize the impact of a token being compromised.
  • Keep the Secret Key Secure: The secret key used to sign the JWT must be kept private and secure. Do not hard-code it in the client.
  • Use Strong Signing Algorithms: Prefer stronger algorithms like RSA or ECDSA over HMAC with weak secret keys.

🧩 10. Conclusion

JSON Web Tokens (JWT) are a widely used and powerful tool for authentication, authorization, and secure information exchange in modern web applications. With its compact structure, self-contained data, and secure signature, JWT simplifies the way applications authenticate and authorize users while maintaining security. When used correctly, JWT provides a robust method to handle secure user sessions, API calls, and data sharing.

JWT is a fundamental tool for any developer building secure, scalable web applications.