Development

Understanding JSON Web Tokens (JWTs)

Development

Understanding JSON Web Tokens (JWTs)

In the digital world where web applications and services interact continuously, ensuring secure communication is paramount. This is where JSON Web Tokens (JWTs) come into play, offering a robust method for safely transmitting information between parties. In this blog post, we’ll unravel what JWTs are, how they work, and why they are a cornerstone of secure online communication. Plus, we’ll walk through some simple examples to demonstrate their usage.

What is a JSON Web Token (JWT)?

A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity-protected with a Message Authentication Code (MAC) and/or encrypted.

How Does JWT Work?

A JWT typically consists of three parts: Header, Payload, and Signature. Here’s a brief overview:

  • Header: The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

  • Payload: The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.

  • Signature: To create the signature part, you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

The result is a three-part structure: header.payload.signature.

Why Use JWTs?

JWTs are a popular choice for authentication and information exchange because:

  • They are self-contained, carrying all necessary information within themselves.

  • They are compact, making them easy to transmit through URLs, POST requests, or HTTP headers.

  • They are mobile-friendly, a critical feature given the prevalence of mobile applications.

Example Usage of JWT

Let’s look at an example of how to create and verify a JWT using Node.js with the jsonwebtoken package.

Creating a JWT

First, you need to install the jsonwebtoken package:

import jwt from "jsonwebtoken";

const secretKey = "your-256-bit-secret-this-is-so-secret";

const user = {
  id: 34,
  name: "Bedirhan",
  isAdmin: true,
};

const token = jwt.sign(user, secretKey, {
  expiresIn: "1m",
  algorithm: "HS256",
});

console.log(token)
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MzQsIm5hbWUiOiJCZWRpcmhhbiIsImlzQWRtaW4iOnRydWUsImlhdCI6MTcxMTM2OTgwNywiZXhwIjoxNzExMzY5ODY3fQ.lQX-af4ojEB9VSqj9qFAxUfUNZjc7-dAsqU2A5d-eNU

Now if we go to jwt debugger to see.

As you can see at left bottom side: our signature is invalid because at verify part i didn't add my secret key. Also when you hover over iat (issued at) you can see date we signed this jwt and exp shows expiration date of jwt.

Conclusion

JSON Web Tokens offer a straightforward and efficient method for secure communication between parties. Their simplicity and ability to be easily passed around make them an excellent choice for authentication, authorization, and information exchange in modern web applications. By incorporating JWTs into your security framework, you can ensure that your application communications are both secure and efficient.


BONUS: HMAC SHA256 & RSA Algorithms for sign/verify JWT'S

HMAC SHA256

  • Type: HMAC (Hash-Based Message Authentication Code) SHA256 is a symmetric signing algorithm.

  • How it Works: It uses a single secret key that the issuer of the JWT and the verifier must both possess. The algorithm takes the header and payload of the JWT, combines them with the secret key, and then applies the SHA-256 hash function to generate the signature.

  • Use Case: HMAC SHA256 is typically used when the sender and receiver of the JWT have a secure channel to exchange the secret key or when the same party is issuing and verifying the token. Its main advantage is its simplicity and the fact that it doesn't require managing public/private key pairs.

  • Security: The security of HMAC SHA256 relies on the secrecy of the shared key. If the key is compromised, the integrity and authenticity of the JWT can no longer be guaranteed.

RSA

  • Type: RSA is an asymmetric signing algorithm.

  • How it Works: Unlike HMAC SHA256, RSA uses a pair of keys: a private key for signing the token and a public key for verifying its signature. The issuer signs the JWT with their private key, and the receivers verify the signature with the corresponding public key.

  • Use Case: RSA is ideal for situations where the issuer and the verifier are not the same entity and cannot securely share a secret key, such as in open systems where tokens need to be verified by third parties.

  • Security: The security of RSA is based on the computational difficulty of factoring large prime numbers. The private key must be kept secure by the issuer; however, the public key can be freely distributed without compromising the security of the tokens.

Key Differences

  • Symmetric vs. Asymmetric: HMAC SHA256 is symmetric, using one secret key for both signing and verification. RSA is asymmetric, using a private key for signing and a public key for verification.

  • Use Cases: HMAC SHA256 is simpler and used in closed systems where the secret key can be securely shared. RSA is used in scenarios where public verification is needed without sharing the sensitive signing key.

  • Performance: Generally, HMAC SHA256 is faster than RSA because it uses simpler cryptographic operations. RSA, being based on public-key cryptography, requires more computational resources, especially as the key size increases to enhance security.

Both HMAC SHA256 and RSA are widely used in securing web communications, including JWT authentication. The choice between them depends on the specific requirements of the application, such as the need for public verification or the ability to securely share a secret key.

Thanks for reading 🚀 see you 👋


In the digital world where web applications and services interact continuously, ensuring secure communication is paramount. This is where JSON Web Tokens (JWTs) come into play, offering a robust method for safely transmitting information between parties. In this blog post, we’ll unravel what JWTs are, how they work, and why they are a cornerstone of secure online communication. Plus, we’ll walk through some simple examples to demonstrate their usage.

What is a JSON Web Token (JWT)?

A JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity-protected with a Message Authentication Code (MAC) and/or encrypted.

How Does JWT Work?

A JWT typically consists of three parts: Header, Payload, and Signature. Here’s a brief overview:

  • Header: The header typically consists of two parts: the type of the token, which is JWT, and the signing algorithm being used, such as HMAC SHA256 or RSA.

  • Payload: The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are three types of claims: registered, public, and private claims.

  • Signature: To create the signature part, you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.

The result is a three-part structure: header.payload.signature.

Why Use JWTs?

JWTs are a popular choice for authentication and information exchange because:

  • They are self-contained, carrying all necessary information within themselves.

  • They are compact, making them easy to transmit through URLs, POST requests, or HTTP headers.

  • They are mobile-friendly, a critical feature given the prevalence of mobile applications.

Example Usage of JWT

Let’s look at an example of how to create and verify a JWT using Node.js with the jsonwebtoken package.

Creating a JWT

First, you need to install the jsonwebtoken package:

import jwt from "jsonwebtoken";

const secretKey = "your-256-bit-secret-this-is-so-secret";

const user = {
  id: 34,
  name: "Bedirhan",
  isAdmin: true,
};

const token = jwt.sign(user, secretKey, {
  expiresIn: "1m",
  algorithm: "HS256",
});

console.log(token)
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MzQsIm5hbWUiOiJCZWRpcmhhbiIsImlzQWRtaW4iOnRydWUsImlhdCI6MTcxMTM2OTgwNywiZXhwIjoxNzExMzY5ODY3fQ.lQX-af4ojEB9VSqj9qFAxUfUNZjc7-dAsqU2A5d-eNU

Now if we go to jwt debugger to see.

As you can see at left bottom side: our signature is invalid because at verify part i didn't add my secret key. Also when you hover over iat (issued at) you can see date we signed this jwt and exp shows expiration date of jwt.

Conclusion

JSON Web Tokens offer a straightforward and efficient method for secure communication between parties. Their simplicity and ability to be easily passed around make them an excellent choice for authentication, authorization, and information exchange in modern web applications. By incorporating JWTs into your security framework, you can ensure that your application communications are both secure and efficient.


BONUS: HMAC SHA256 & RSA Algorithms for sign/verify JWT'S

HMAC SHA256

  • Type: HMAC (Hash-Based Message Authentication Code) SHA256 is a symmetric signing algorithm.

  • How it Works: It uses a single secret key that the issuer of the JWT and the verifier must both possess. The algorithm takes the header and payload of the JWT, combines them with the secret key, and then applies the SHA-256 hash function to generate the signature.

  • Use Case: HMAC SHA256 is typically used when the sender and receiver of the JWT have a secure channel to exchange the secret key or when the same party is issuing and verifying the token. Its main advantage is its simplicity and the fact that it doesn't require managing public/private key pairs.

  • Security: The security of HMAC SHA256 relies on the secrecy of the shared key. If the key is compromised, the integrity and authenticity of the JWT can no longer be guaranteed.

RSA

  • Type: RSA is an asymmetric signing algorithm.

  • How it Works: Unlike HMAC SHA256, RSA uses a pair of keys: a private key for signing the token and a public key for verifying its signature. The issuer signs the JWT with their private key, and the receivers verify the signature with the corresponding public key.

  • Use Case: RSA is ideal for situations where the issuer and the verifier are not the same entity and cannot securely share a secret key, such as in open systems where tokens need to be verified by third parties.

  • Security: The security of RSA is based on the computational difficulty of factoring large prime numbers. The private key must be kept secure by the issuer; however, the public key can be freely distributed without compromising the security of the tokens.

Key Differences

  • Symmetric vs. Asymmetric: HMAC SHA256 is symmetric, using one secret key for both signing and verification. RSA is asymmetric, using a private key for signing and a public key for verification.

  • Use Cases: HMAC SHA256 is simpler and used in closed systems where the secret key can be securely shared. RSA is used in scenarios where public verification is needed without sharing the sensitive signing key.

  • Performance: Generally, HMAC SHA256 is faster than RSA because it uses simpler cryptographic operations. RSA, being based on public-key cryptography, requires more computational resources, especially as the key size increases to enhance security.

Both HMAC SHA256 and RSA are widely used in securing web communications, including JWT authentication. The choice between them depends on the specific requirements of the application, such as the need for public verification or the ability to securely share a secret key.

Thanks for reading 🚀 see you 👋


© 2023 Bedirhan

Have a great day

© 2023 Bedirhan

Have a great day