0% found this document useful (0 votes)
26 views7 pages

Introduction To JWT

JWT, or JSON Web Token, is a compact and self-contained method for securely transmitting information as a JSON object, commonly used for authentication and information exchange in web applications. It consists of three parts: header, payload, and signature, which ensure integrity and authenticity. The document also covers installation, generation, verification, and common errors associated with JWTs.

Uploaded by

ermias70ne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views7 pages

Introduction To JWT

JWT, or JSON Web Token, is a compact and self-contained method for securely transmitting information as a JSON object, commonly used for authentication and information exchange in web applications. It consists of three parts: header, payload, and signature, which ensure integrity and authenticity. The document also covers installation, generation, verification, and common errors associated with JWTs.

Uploaded by

ermias70ne
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Introduction to JWT

Authentication using JWT


JWT, or JSON Web Token, is an open standard (RFC 7519) used for securely
transmitting information between parties as a JSON object. It is commonly used
for authentication and information exchange in web applications.

Key Features of JWT:


1. Compact: JWTs are small, making them easy to transmit via URLs, HTTP
headers, or cookies.

2. Self-contained: They contain all the information needed for authentication,


reducing the need for repeated database queries.

3. Structure: A JWT consists of three parts:

Header: Contains metadata about the token, including the type (JWT) and
the signing algorithm (e.g., HMAC, RSA).

Payload: Contains the claims (the information being transmitted), which


can include user details and permissions.

Signature: Created by combining the encoded header, payload, and secret


or private key to prevent tampering.

4. Stateless: JWTs can be verified without needing to store session information


on the server, making them suitable for distributed systems.

Common Use Cases:


Authentication: After a user logs in, a JWT can be issued, which the user can
then use for subsequent requests.

Information Exchange: Securely transmitting information between parties,


ensuring the integrity and authenticity of the data.

How to install JWT?

Introduction to JWT 1
npm install jsonwebtoken

// For TypeScript users


npm install @types/jsonwebtoken --save-dev

Structure of JWT
A valid JWT consists of three parts (header, payload, and signature) separated by
periods ( . ).

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZ

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

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

// Signature
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
your-256-bit-secret
)

Introduction to JWT 2
In the context of JSON Web Tokens (JWTs), the signature is a cryptographic
element that ensures the integrity and authenticity of the token. It is created using
a signing algorithm and a secret key (for HMAC) or a private key (for asymmetric
algorithms like RSA).

Purpose of the Signature


1. Integrity: The signature verifies that the token has not been altered. If any part
of the token (header or payload) is changed after the token is signed, the
signature will no longer match, indicating potential tampering.

2. Authenticity: The signature confirms that the token was issued by a legitimate
source. Only someone with access to the secret key (for HMAC) or private key
(for RSA) can generate a valid signature.

How the Signature is Created


The signature is generated by:

1. Combining the Header and Payload: The header and payload are Base64-
URL encoded and concatenated with a period ( . ) in between.

Copy
signatureInput = base64UrlEncode(header) + "." + base64UrlEncode(payload)

2. Applying the Signing Algorithm: The combined string is then processed with
a cryptographic signing algorithm (e.g., HMAC SHA-256) along with the secret
or private key.
Copy
signature = HMACSHA256(signatureInput, your-256-bit-secret)

💡 HMACSHA256 refers to a specific cryptographic algorithm that


combines the HMAC (Hash-based Message Authentication Code)
construction with the SHA-256 (Secure Hash Algorithm 256-bit) hash
function.

How to generate a JWT?

Introduction to JWT 3
We can use the sign method from JWT to generate a JWT by providing three main
information to the method.

The payload that we want to encrypt

The JWT Secret key that is used for signature and later used to decode the
payload from the JWT

The expire date for the JWT

💡 If you don't provide an


(JWT) using libraries like
expiresIn value when signing a JSON Web Token
jsonwebtoken , the token will not have an
expiration time set. This means the token will be valid indefinitely, until it
is manually invalidated or the secret key is changed.

Implications of Not Setting expiresIn :


1. Security Risk: An indefinitely valid token can pose a security risk if it
gets compromised, as there would be no expiration to limit its
validity.

2. Best Practices: It is generally recommended to always set an


expiration time for JWTs to enhance security. Common practices
suggest using short expiration times for access tokens (e.g., 15
minutes to 1 hour) and longer times for refresh tokens.

The expiresIn option for setting the expiration time of a JSON Web Token (JWT) can
be specified in various formats when using libraries like jsonwebtoken . Here are the
common formats you can use:

Common Formats for expiresIn


1. Seconds:

You can specify the expiration time in seconds as a number.

Example: 3600 (which represents 1 hour).

2. String Format:

Introduction to JWT 4
You can use a string to specify the expiration time in a more readable way.

The string can include:

Seconds: "60" for 1 minute

Minutes: "10m" for 10 minutes

Hours: "1h" for 1 hour

Days: "7d" for 7 days

import { sign } from "jsonwebtoken";


import config from "../../config";

/**
* Generate or sign token
* @param {string} id
* @returns {string} token
*/
export default (id: string, role: string) => {
return sign({ id, role }, config.jwt.secret, {
expiresIn: "90d",
});
};

How to decode or verify a JWT?


We can use the verify method from JWT to decode the encrypted data from the
JWT token by providing the token itself and the JWT secret used to generate it.

Token

JWT Secret

The response of the verify method or the decoded data includes the following key
value pairs.

Payload provided during signing the token

iat - Issued at or the creation timestamp

Introduction to JWT 5
exp - Token expire date provided during token creation

import { JwtPayload, verify } from "jsonwebtoken";


import config from "../../config";

interface ICustomJwtPayload extends JwtPayload {


id: string;
role: string;
}

/**
* Verify token
* @param {string} token
* @returns {JwtPayload} Jwt payload
*/
export default (token: string): ICustomJwtPayload => {
return verify(token, config.jwt.secret) as ICustomJwtPayload;
};

Types of JWT errors


There are two types of errors that need to be handled when it comes to JWT.

Token Expired Error


The TokenExpiredError is an error that occurs when a JSON Web Token (JWT) is used
after its expiration time has passed. This error is commonly encountered when
validating or verifying a token that has an exp claim indicating when it should
expire.

Causes of TokenExpiredError
1. Expired Token: The primary reason for this error is that the token has
exceeded its allowed lifespan. If the exp claim in the token is set to a time in
the past, any attempt to verify or use that token will result in a TokenExpiredError .

Introduction to JWT 6
2. Incorrect System Time: If the server's system time is out of sync (e.g., due to
misconfiguration), it may incorrectly interpret the expiration time.

Json Web Token Error


is an error thrown by libraries like jsonwebtoken when there is a
JsonWebTokenError

problem with the JWT that is being verified or decoded. This error indicates that
the token is not valid for some reason, but it is not specifically about expiration.

Common Causes of JsonWebTokenError


1. Invalid Signature:

The token's signature does not match the expected signature when
verified with the secret key or public key. This could happen if the token
has been tampered with.

2. Malformed Token:

The token does not conform to the JWT format. A valid JWT consists of
three parts (header, payload, and signature) separated by periods ( . ).

3. No Signature:

The token is missing a signature, making it impossible to verify.

4. Incorrect Secret or Algorithm:

The secret or public key used for verification does not match the one used
to sign the token, or the specified algorithm during verification is incorrect.

Introduction to JWT 7

You might also like