JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties. It is commonly used for authentication and information exchange.
A JWT consists of three parts: Header, Payload, and Signature. Each part is Base64Url encoded and concatenated with dots.
To generate a JWT token, you'll need a secret key and the payload data you want to encode.
const jwt = require('jsonwebtoken');
function generateToken(user) {
const payload = { id: user.id, email: user.email };
const secret = 'your-256-bit-secret';
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
return token;
}
// Use < > so that they don't get executed.
The `generateToken` function creates a JWT token using the user's ID and email as payload, signs it with a secret key, and sets an expiration time of 1 hour.
Verification ensures the token is valid and has not been tampered with.
function verifyToken(token) {
const secret = 'your-256-bit-secret';
try {
const decoded = jwt.verify(token, secret);
return decoded;
} catch (err) {
throw new Error('Invalid token');
}
}
// Use < > so that they don't get executed.
The `verifyToken` function checks the validity of the token using the same secret key. If valid, it returns the decoded payload; otherwise, it throws an error.
Middleware can be used to protect routes by verifying tokens before granting access.
const express = require('express');
const app = express();
function authMiddleware(req, res, next) {
const token = req.headers['authorization'];
if (!token) return res.status(403).send('Token required');
try {
const decoded = jwt.verify(token, 'your-256-bit-secret');
req.user = decoded;
next();
} catch (err) {
res.status(401).send('Invalid token');
}
}
app.use('/protected-route', authMiddleware, (req, res) => {
res.send('This is a protected route');
});
// Use < > so that they don't get executed.
The `authMiddleware` function checks for a token in the request headers, verifies it, and attaches the decoded user to the request object. If the token is invalid, it sends a 401 response.
Tokens can be refreshed to extend their validity without requiring the user to log in again.
function refreshToken(oldToken) {
try {
const decoded = jwt.verify(oldToken, 'your-256-bit-secret', { ignoreExpiration: true });
const newToken = jwt.sign({ id: decoded.id, email: decoded.email }, 'your-256-bit-secret', { expiresIn: '1h' });
return newToken;
} catch (err) {
throw new Error('Invalid token');
}
}
// Use < > so that they don't get executed.
The `refreshToken` function decodes the old token without checking its expiration, then generates a new token with a fresh expiration time.
Always use HTTPS to secure the transport of JWTs, preventing interception and tampering.
// Ensure your server is configured to use HTTPS
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('path/to/private.key'),
cert: fs.readFileSync('path/to/certificate.crt')
};
https.createServer(options, app).listen(443, () => {
console.log('Secure server running on port 443');
});
// Use < > so that they don't get executed.
Using HTTPS ensures that all data, including JWTs, is encrypted in transit, providing a secure layer against network attacks.
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies