xxxxxxxxxx
if (Date.now() >= exp * 1000) {
return false;
}
xxxxxxxxxx
const JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjEyMzQ1Njc4OTAsIm5hbWUiOiJKb2huIERvZSIsImlhdCI6MTUxNjIzOTAyMn0.1c_yQjnMZfKUb4UTDE_WvbC71f8xxtyMsdqKKkI1hF8";
const jwtPayload = JSON.parse(window.atob(JWT.split('.')[1]))
const isExpired = Date.now() >= jwtPayload.exp * 1000;
xxxxxxxxxx
const jwt = require('jsonwebtoken');
// Middleware to check JWT token expiration
const checkTokenExpiration = (req, res, next) => {
// Get the token from the Authorization header
const token = req.headers.authorization;
if (token) {
try {
// Verify and decode the token
const decodedToken = jwt.verify(token, 'your_secret_key');
// Check the expiration time of the token
const { exp } = decodedToken;
const currentTime = Math.floor(Date.now() / 1000);
if (currentTime > exp) {
// Token has expired
return res.status(401).json({ message: 'Token has expired' });
}
} catch (error) {
// Error occurred while decoding or verifying the token
return res.status(401).json({ message: 'Invalid token' });
}
} else {
// No token provided
return res.status(401).json({ message: 'No token provided' });
}
// Token is valid, proceed to the next middleware or route handler
next();
};
// Apply the middleware to the desired routes
app.get('/protected', checkTokenExpiration, (req, res) => {
// This route will only be accessible if the token is valid and not expired
res.json({ message: 'Access granted' });
});