JWT Token NodeJS
JWT Token NodeJS
● Definition: JWT is a specific type of token format defined by the JSON Web
Token standard (RFC 7519). It is a compact and self-contained means of
transmitting information between parties as a JSON object.
● Structure: JWTs consist of three parts: header, payload, and signature. They
are typically encoded and signed using cryptographic algorithms.
● Usage: JWTs are commonly used for authentication and authorization in web
applications and APIs. They can store user claims, such as user ID, roles,
permissions, and custom data, in a secure and portable format.
● Statelessness: JWTs are stateless, meaning the server does not need to store
session information. This makes them suitable for distributed architectures and
scalable systems.
JWT Structure
A JWT is composed of three sections separated by dots (.), following the format
header.payload.signature.
1. Header: Contains metadata about the type of token and the cryptographic
algorithms used to secure it. It typically consists of two parts:
○ Typ (Type): Specifies the type of token, usually set to "JWT".
○ Alg (Algorithm): Indicates the cryptographic algorithm used to sign the
token, such as HMAC SHA256 or RSA.
2. Payload: Contains the claims or statements about the subject (user) and any
additional data. It consists of a set of claims that represent assertions about the
user, such as their identity, roles, or permissions. Claims are categorized into
three types:
○ Reserved Claims: Predefined claims standardized by the JWT
specification, such as iss (issuer), sub (subject), aud (audience), exp
(expiration time), and iat (issued at).
○ Public Claims: Custom claims defined by the application developer to
convey information about the user.
○ Private Claims: Custom claims agreed upon by parties that exchange
JWTs, not registered or standardized.
3. Signature: Verifies the integrity of the token and ensures that it has not been
tampered with during transmission. It's created by taking the encoded header,
encoded payload, a secret (for HMAC algorithms), and applying the specified
algorithm to generate the signature.
Authentication Flow
JWT Functions
jwt.sign():
● This function is used to generate a new JWT token based on the provided
payload and options.
● It takes three parameters:
○ payload: This is the data you want to include in the token. It can be any
JSON object containing user information, metadata, or any other relevant
data.
○ secretOrPrivateKey: This is the secret key used to sign the token. It
can be a string or a buffer containing a secret cryptographic key.
○ options (optional): These are additional options that control the behavior
of the token generation process, such as expiration time (expiresIn),
algorithm (algorithm), and more.
jwt.verify():
● This function is used to verify and decode a JWT token to retrieve the original
payload.
● It takes three parameters:
○ token: The JWT token to be verified.
○ secretOrPublicKey: The secret key or public key used to verify the
token's signature. If the token was signed using a symmetric algorithm
(e.g., HMAC), you need to provide the same secret key used to sign the
token. If it was signed using an asymmetric algorithm (e.g., RSA), you need
to provide the public key corresponding to the private key used for signing.
○ options (optional): Additional options for verification, such as algorithms
(algorithms), audience (audience), issuer (issuer), and more.
// Verify and decode the JWT token
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
// Token verification failed
console.error('Token verification failed:', err.message);
} else {
// Token verification successful
console.log('Decoded token:', decoded);
}
});
1. Signup Route (/signup): This route will handle user registration and issue a
JWT token upon successful registration.
2. Login Route (/login): This route will handle user login and issue a new JWT
token upon successful authentication.
3. Protected Routes: These routes will be accessed only by providing a valid JWT
token.
Install JWT
First, you'll need to install the necessary packages for working with JWT. In Node.js,
you can use packages like jsonwebtoken to generate and verify JWTs.
Create a JWT Auth Middleware function, which is responsible for authentication via
Tokens
// jwtAuthMiddleware.js
const jwt = require('jsonwebtoken');
try {
// Verify the JWT token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Attach user information to the request object
req.user = decoded;
next();
} catch (err) {
console.error(err);
res.status(401).json({ error: 'Invalid token' });
}
};
module.exports = jwtAuthMiddleware;
// Login route
router.post('/login', async (req, res) => {
try {
// Extract username and password from request body
const { username, password } = req.body;
// If user does not exist or password does not match, return error
if (!user || !(await user.comparePassword(password))) {
return res.status(401).json({ error: 'Invalid username or
password' });
}
When the server receives this request, it parses the Authorization header to
extract the JWT token.
The split(' ') method separates the header value into an array of substrings using
the space (' ') character as the delimiter. The [1] index accesses the second element
of this array, which is the JWT token.