JWT Token Generation and Verification in JavaScript
Tags: javascript, jwt, webdev, token
Published: 2024-04-08 05:48:58

JWT stands for JSON Web Token. It is a compact, URL-secure approach of representing claims securely between  events. These claims are represented as JSON items which might be base64url encoded and digitally signed. JWTs are commonly used for authentication and authorization in net applications and APIs.

Here's a breakdown of the components of a JWT:

1. Header: The header commonly consists of  parts: the type of token, that's JWT, and the signing algorithm getting used, such as HMAC SHA256 or RSA. This a part of the JWT is base64url encoded.

2. Payload: The payload incorporates the claims. Claims are statements approximately an entity (generally, the person) and extra records. There are three forms of claims: registered, public, and personal claims. The payload is likewise base64url encoded.

3. Signature: The signature is created with the aid of combining the encoded header, the encoded payload, a mystery (in case of HMAC), and a cryptographic set of rules detailed inside the header. This signature guarantees that the JWT isn't always tampered with at some stage in transmission.

When JWTs are used for authentication, after a consumer efficiently logs in, the server creates a JWT and sends it returned to the customer. The consumer then normally stores this JWT, often in nearby garage or a cookie, and includes it within the header of next requests to the server. The server verifies the JWT's signature to make sure its authenticity and extracts the user facts from the payload.

JWTs are high-quality due to the fact they're stateless, which means servers do not want to shop session statistics. They can be easily transmitted as URL parameters, in HTTP headers, or as part of POST request bodies. Additionally, JWTs may be used throughout distinct domain names, making them appropriate for unmarried signal-on (SSO) eventualities.

However, it is vital to deal with JWTs securely, especially regarding how they may be stored and transmitted. Storing JWTs in cookies with suitable safety flags or the usage of HTTPS to encrypt transmission are commonplace practices to beautify protection. Also, JWTs should not incorporate sensitive statistics that might be exploited if the token is compromised.


Let's create a easy example of ways JWT is probably utilized in a web utility for authentication.

Suppose we've got a primary authentication system with a server and a purchaser (e.G., a web browser). Here's how the waft would possibly appearance:

1. User Login:
   - The person enters their credentials (e.G., username and password) at the customer-facet (e.G., a login shape in a web browser).
   - The patron sends the credentials to the server for authentication.

2. Server Authentication:
   - The server verifies the credentials. If they're legitimate, the server generates a JWT containing a few consumer statistics (e.G., user ID or username) and signs and symptoms it with a secret key.
   - The server sends the JWT back to the patron as a part of the response.

3. Client Storage:
   - The purchaser gets the JWT and stores it securely. This is probably in neighborhood garage, a consultation cookie, or another stable garage mechanism.

4. Subsequent Requests:
   - For subsequent requests to blanketed sources on the server (e.G., getting access to user-specific records or appearing movements), the customer consists of the JWT in the request headers.
   - The server verifies the JWT's signature the usage of the secret key. If the signature is valid, the server extracts the consumer records from the JWT and proceeds with the request.
   - If the signature is invalid or the JWT is expired, the server denies get right of entry to or asks the purchaser to authenticate again.

Here's a simplified example of a JWT:

JWT: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.EyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

This JWT consists of three parts separated by way of intervals:

1. Header: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9
2. Payload: eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
three. 
3. Signature: SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Decoding each part (e.G., the use of a base64 decoder) could screen the header and payload contents. The signature is used to affirm the integrity of the JWT.

In a actual-international scenario, the payload might incorporate more useful facts, together with consumer roles, permissions, or different relevant records wished for authentication and authorization.

Code Example:
// Base64URL encoder/decoder features
feature base64urlEncode(str) 
    return btoa(str).Update(/+/g, '-').Replace(///g, '_').Update(/=/g, '');


feature base64urlDecode(str) 
    return atob(str.Update(/-/g, '+').Replace(/_/g, '/'));


// Generate JWT token
function generateJWT(payload, secret) 
    const header =  alg: 'HS256', typ: 'JWT' ;
    const encodedHeader = base64urlEncode(JSON.Stringify(header));
    const encodedPayload = base64urlEncode(JSON.Stringify(payload));
    const signature = base64urlEncode(crypto.CreateHmac('sha256', mystery).Replace(encodedHeader + '.' + encodedPayload).Digest('base64'));
    return encodedHeader + '.' + encodedPayload + '.' + signature;


// Verify JWT token
feature verifyJWT(token, secret) 
    const [encodedHeader, encodedPayload, signature] = token.Break up('.');
    const calculatedSignature = base64urlEncode(crypto.CreateHmac('sha256', mystery).Update(encodedHeader + '.' + encodedPayload).Digest('base64'));
    return calculatedSignature === signature;


// Example usage
const payload =  username: 'veer123', role: 'admin' ;
const secretKey = 'your_secret_key';
const token = generateJWT(payload, secretKey);
console.Log('Generated JWT:', token);

const isVerified = verifyJWT(token, secretKey);
console.Log('Is token demonstrated?', isVerified);