I have this problem with my authentication that only happens upon refresh. My authentication middleware looks like this:
const jwt = require('jsonwebtoken');
require("dotenv").config();
const express = require('express');
const verifyToken = (req, res, next) => {
const {cookies} = req;
if ('token' in cookies) {
jwt.verify(cookies.token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
if (err) {
console.log('COOKIE ERROR')
res.redirect('/../notLoggedIn');
}
req.userId = decoded.user_id;
next();
});
} else {
console.log('NO VALID TOKEN')
res.redirect('/../notLoggedIn');
}
}
module.exports = verifyToken;
It works perfectly when going into routes, but if I'm already in an authRoute, for example "profile", and refresh the page, I will get the console.log "NO VALID TOKEN". But then when I check the cookies I can see that it is there. My only conclusion is that the cookie dissapears for a split second when refreshing and the authentication middleware is fired before the cookie comes back.
Anyone knows how to fix this?
Ps. My setup for the sessioncookies looks like this:
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000*60*30,
//secure: true, //Only have true when deploying on https
sameSite: true
},
rolling: true,
httpOnly: true,
}));
I have tried with multiple configurations but still can't get it to work.
CodePudding user response:
I think the maxAge
property in the session should just have 1000*60*30
instead of Date.now() 1000*60*30
.
Link to the express-session documentation
CodePudding user response:
I think you have to share a snippet code that contains a set cookie logic. It might be the problem