JWT || JSON Web Token

Disclaimer: The content of this article represents my personal notes Only. If any mistakes or inaccuracies are identified, I welcome readers to provide feedback and corrections in the comments section.


JWT stands for JSON Web Token. It is a compact and self-contained means of transmitting information securely between two parties as a JSON object. JWTs are commonly used for authentication and authorization purposes in web applications.

A JWT consists of three parts:

  • a header,

  • a payload,

  • and a signature.

The header typically consists of two parts:

  • the type of the token, which is JWT,

  • and the algorithm used to sign the token, such as HMAC SHA256 or RSA.

The payload contains the claims or statements about the user or any other information that needs to be transmitted. Claims can include things like the user's identity, permissions, or any custom data relevant to the application.

The signature is created by taking the encoded header, encoded payload, a secret key, and the signing algorithm specified in the header. The signature is used to verify that the message hasn't been tampered with and ensures the authenticity of the sender.

Since JWTs are self-contained, the server does not need to maintain a session state, which can benefit distributed or stateless architectures. However, it's important to secure the JWTs properly and use appropriate measures to prevent unauthorized access or token tampering.

NPM Package

JSON Web Token implementation for node.js (github.com)

Install

npm install jsonwebtoken

Usage

sign() Function:

What is it?

The sign() function is used to generate a JSON Web Token (JWT) by signing a payload with a secret or private key.

Why use this function?

Use this function when you want to create a JWT for authentication or authorization purposes.

Definition:

Generates a JWT by signing the provided payload with a secret or private key.

Syntax:

jwt.sign(payload, secretOrPrivateKey, [options, callback])

Example:

const jwt = require('jsonwebtoken');

const payload = { id: 123, username: 'john_doe' };
const secretKey = 'your-secret-key';

const token = jwt.sign(payload, secretKey);
console.log(token);

Code Explanation:

The sign() function takes a payload (an object containing data to be included in the token), a secretOrPrivateKey (key used to sign the token), and optional options and callback. In the example, a payload object is defined, and a secret key is used to sign the token. The resulting token is printed to the console.

verify() Function:

What is it?

The verify() function is used to verify the authenticity and integrity of a JWT by checking its signature.

Why use this function?

Use this function when you want to ensure the validity of a received JWT.

Definition:

Verifies the authenticity and integrity of a JWT by checking its signature.

Syntax:

jwt.verify(token, secretOrPublicKey, [options, callback])

Code Example:

const jwt = require('jsonwebtoken');

const token = 'your-jwt-token';
const secretKey = 'your-secret-key';

jwt.verify(token, secretKey, (err, decoded) => {
  if (err) {
    console.error('Token verification failed:', err.message);
    return;
  }

  console.log(decoded);
});

Code Explanation:

The verify() function takes a token (JWT to be verified), a secretOrPublicKey (key used to verify the signature), and optional options and callback. In the example, the verify() function is called with the token and the secret key. If the token is successfully verified, the decoded payload is logged to the console. If verification fails, an error message is printed.

decode() Function:

What is it?

The decode() function is used to decode the payload of a JWT without verifying its signature.

Why use this function?

Use this function when you only need to extract the information from a JWT without verifying its authenticity.

Definition:

Decodes the payload of a JWT without verifying its signature.

Syntax:

jwt.decode(token, [options])

Code Example:

const jwt = require('jsonwebtoken');

const token = 'your-jwt-token';

const decoded = jwt.decode(token);
console.log(decoded);

Code Explanation:

The decode() function takes a token and optional options. In the example, the decode() function is called with the token, and the decoded payload (without verification) is printed to the console.

Remember to replace 'your-secret-key' and 'your-jwt-token' with the actual secret key and JWT token, you are working within your code.


Key Points of the node-jsonwebtoken library are:

  • The library is a JSON Web Token (JWT) implementation for Node.js.

  • JWTs are a standard way of representing claims securely between parties.

  • The library supports HMAC, RSA, and ECDSA algorithms for signing and verifying JWTs.

  • The library can be used to create, sign, verify, and decode JWTs.

  • The library is open-source and available on GitHub.

Here are some additional details about each of these points:

  • JWTs are a standard way of representing claims securely between parties. A JWT is a self-contained token that can be used to secure various applications, including web applications, APIs, and mobile apps.

  • The node-jsonwebtoken library supports HMAC, RSA, and ECDSA algorithms for signing and verifying JWTs. HMAC is a hash-based message authentication code that uses a secret key to sign a JWT. RSA and ECDSA are public-key algorithms that use a public key to sign a JWT and a private key to verify a JWT.

  • The node-jsonwebtoken library can be used to create, sign, verify, and decode JWTs. To create a JWT, you need to provide the claims that you want to include in the JWT, the signing algorithm, and the secret key or public key.

    • To sign a JWT, you use the library's sign() method.

    • To verify a JWT, you use the library's verify() method.

    • To decode a JWT, you use the library's decode() method.