xxxxxxxxxx
const checkTokenExpirationMiddleware = store => next => action => {
const token =
JSON.parse(localStorage.getItem("user")) &&
JSON.parse(localStorage.getItem("user"))["token"];
if (jwtDecode(token).exp < Date.now() / 1000) {
next(action);
localStorage.clear();
}
next(action);
};
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' });
});