I tried to see if my cookies is working ,so here's my code
const RedisStore = connectRedis(session)
const redisClient = redis.createClient()
app.use(
session({
//name: 'qid',
store: new RedisStore({ //ttl: how long it should last
client: redisClient,
//disableTTL :true, //make sure session last forever
//disableTouch: true, // make sure it does'nt have to update the last time it's ttl
}),
cookie:{
maxAge: 1000*60*60*24*365*10, //10 years
path: "/"
//httpOnly:true, //javascript front end can't access
//sameSite:'none', // csrf
//secure:false
//secure: __prod__ //cookie only works in https
},
saveUninitialized:true, //automatically create a empty session on default
secret: 'some secret', //env
resave: false,
})
)
app.listen(4000,()=>{
console.log('server stared on localhost:4000')
})
app.get('/products', (req,res,next) => {
console.log(req.session);
if(!req.session.userId){
req.session.userId = 1
}else{
req.session.userId = req.session.userId +1
}
console.log(req.session.userId) //test if work
res.send("hello")
})
So here's the thing, when I connect to localhost:4000/products, In the cookie session, I can only see these
But when I print out the results on vscode console, I can see the number is growing like below , so I do have a session, it's just not showing on the browser , can anyone tell me why is that?
server stared on localhost:4000
Session {
cookie: {
path: '/',
_expires: 2031-08-18T12:59:30.827Z,
originalMaxAge: 315360000000,
httpOnly: true
},
userId: 10
}
11
Session {
cookie: {
path: '/',
_expires: 2031-08-18T13:00:37.257Z,
originalMaxAge: 315360000000,
httpOnly: true
},
userId: 11
}
12
So I got a solution after a lot of tests, So if you only set your cookie to same-site:"none" without secure options ,it would be like my situation,but if you want to turn on secure option your endpoint have to be https, so I don't think this was the answer, and you can change to lax or other options it would act normal in your localhost,
Work in local host
lax
(don't set same site)
But due to secure policy https://www.chromium.org/updates/same-site you can't not pass cookie to some certain website (in my case I want to test cookies in my graphql apollo studio) without setting same-site:"none" secure, so I use mkcert to use https in my localhost
https://web.dev/how-to-use-local-https/ , and everything works,
Work
samesite : none
secure : true
https:yourendpoint
Related
I've been working on this problem for a while, and I am stumped.
I am using express-session with connect-redis as a store for the sessions. I am using typescript.
I added this to the top of my server file and I am able to access the fields without any typescript errors.
declare module "express-session" {
interface SessionData {
userId: string;
role: UserRole;
}
}
When I log a user in, I set the extra SessionData fields.
request.session.userId = user._id.toHexString();
request.session.role = user.role;
console.log(request.session);
Via Postman, I can see that the cookie is set and returned. Additionally, I checked Redis for the session key and the session is correct. e.g.
{\"cookie\":{\"originalMaxAge\":604800000,\"expires\":\"2023-01-23T17:34:05.158Z\",\"secure\":true,\"httpOnly\":true,\"path\":\"/\"},\"userId\":\"1234\",\"role\":\"userRole\"}
However, the extra fields I added to SessionData are not being populated after calling the session middleware. Instead of getting:
Session {
cookie: {
path: '/',
_expires: 2023-01-23T17:52:49.153Z,
originalMaxAge: 604800000,
httpOnly: true,
secure: true
},
userId: '1234',
role: 'userRole'
}
I get:
Session {
cookie: {
path: '/',
_expires: 2023-01-23T17:52:52.339Z,
originalMaxAge: 604800000,
httpOnly: true,
secure: true
}
}
This is how I am calling the session middleware:
const sessionOptions: SessionOptions = {
secret: "secret key",
resave: true,
saveUninitialized: true,
cookie: { secure: true, httpOnly: true },
store: store,
};
app.use(session(sessionOptions));
I thought it may have been an issue with redis, but the key/value is being persisted. I thought maybe it was an issue with connect-redis, so I used the default MemoryStore, but that doesn't work either.
Any help would be appreciated!
Of course right after I ask this question I figure out what the answer is...
First, don't manually set the cookie for the session id in the response. It will automatically be done for you.
Second, ensure that secure is FALSE on localhost.
I have a server that has its own domain and is using HTTPS. I have a website that has its own domain and is using HTTPS as well.
On the home page of the website, there is a login button and a sign up button. Both buttons lead to forms to execute their respective tasks, and both forms send requests to the server that respond with cookies, or at least that's what they are supposed to do.
I am using express-session in combination with Redis to store the session ids. Here is the config for that (connectToRedis is simply a function that returns a RedisClient):
const RedisStore = connectRedis(session);
const redisClient = await connectToRedis();
app.use(
session({
store: new RedisStore({
client: redisClient,
}),
cookie: {
httpOnly: true,
secure: true,
sameSite: "lax",
maxAge: TEN_YEARS,
},
resave: false,
saveUninitialized: false,
secret: SECRET,
name: AUTH_COOKIE,
})
);
For some reason the cookies are not being sent in the requests. The Set-Cookie header isn't even showing up! I tried changing SameSite to none (article), but that didn't work.
This is my first time deploying a production website, so all this HTTPS stuff is kind of new to me.
Thanks for your help, and if you need any extra information, please let me know.
IMPORTANT UPDATE:
Finally, I have made some progress (all it took was a pizza break).
I added the path key to my cookie config and gave it the value of /. I also set proxy to true.
So now it looks like this:
const RedisStore = connectRedis(session);
const redisClient = await connectToRedis();
app.use(
session({
store: new RedisStore({
client: redisClient,
}),
cookie: {
httpOnly: true,
secure: true,
sameSite: "none",
maxAge: TEN_YEARS,
path: "/",
},
resave: false,
saveUninitialized: false,
secret: SECRET,
name: AUTH_COOKIE,
proxy: true,
})
);
With this, the cookie is finally appearing in the requests, but it isn't being set in the browser...
To make my webapp ready for production, I wanted to set the session cookie property "secure" from false to true.
The app is hosted by Aws and is built like this:
Route53 -> CloudFront -> ELB (no cluster, only SingleApp)
CloudFront is used to make the app accessible via SSL. The Nodejs app listens on an HTTP port.
Unfortunately the SessionCookie is not set.
If I set secure to false, the login works and the session cookie is set. So it only seems to depend on this property.
I also set "trust proxy" to true, but unfortunately without success.
Express.js:
const ExpressApp=express();
ExpressApp.set("trust proxy", (ip)=>{
return true;
});
...
session:
const expiryDate = new Date( Date.now() + 60 * 60 * 1000 ); // 1 hour
return session({
genid: (req) => {
return uuid() // use UUIDs for session IDs
},
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
proxy:true,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
rolling: true,
cookie:{
secure:true,
httpOnly:true,
expires: expiryDate
}
})
CloudFront:
https://pasteboard.co/Ib9mTED.png
I am not able to view req.session saved data after storing userId after user logs in.
When I console.log the session from the login function I get the proper data...
Session {
cookie:
{ path: '/',
_expires: 2019-02-23T12:17:24.134Z,
originalMaxAge: 7200000,
httpOnly: true,
sameSite: true,
secure: false },
userId: 4 }
But when I console.log(req.session) from other routes after that I get a new blank session
Session {
cookie:
{ path: '/',
_expires: 2019-02-23T12:12:47.282Z,
originalMaxAge: 7200000,
httpOnly: true,
sameSite: false,
secure: false } }
I am working on my localhost using React frontend on port 3000 and Node/Express with express-session and redis-connect. When I view my Redis I see the stored session properly.
This is my session code...
app.use(
session({
store,
name: 'sid',
saveUninitialized: false,
resave: false,
secret: 'secret',
cookie: {
maxAge: 1000 * 60 * 60 * 2,
sameSite: true,
secure: false
}
})
)
I have tried all different values for these options and nothing works. Please help!
The answer came from a mix of answers from RobertB4 https://github.com/expressjs/session/issues/374
Apparently this problem is common when using CORS middleware and fetch api. In all of your fetch calls you need to send a credentials property set to 'include' and in your cors middleware you need to set an option to credentials: true. It is not good enough to do one or the other, you must do both...
fetch('url', {
credentials: 'include'
})
const corsOptions = {
credentials: true
}
I'm using NodeJS + express + express-session to persist a userID from anywhere in the application.
On the first route, my session is defined
userProfileRoutes.route('/authentication').post((req, res) => {
req.session.userID = 10; //example
console.log(req.session)
}
The result of the console.log is:
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
secure: true },
userID: 10 } // this is the right value
But then, from a different route, I can't see the value:
userProfileRoutes.route('/edit').get(function (req, res) {
console.log('After the nav edit route');
console.log(req.session);
}
And this prints
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true,
secure: true }
} // ID VARIABLE DISAPEARS HERE
I am configuring express-session using these parameters:
app.use(session({
secret: 'secret',
proxy: true,
resave: false,
saveUninitialized: true,
withCredentials: true,
cookie: { secure: true },
store: new MongoStore({ mongooseConnection: db })
}));
Why is my userID not persisted between requests and on all routes?
You are setting cookie: {secure: true} but trying to access your server using HTTP.
From the express-session documentation:
cookie.secure
Note be careful when setting this to true, as compliant clients will not send the cookie back to the server in the future if the browser does not have an HTTPS connection.
Please note that secure: true is a recommended option. However, it requires an https-enabled website, i.e., HTTPS is necessary for secure cookies. If secure is set, and you access your site over HTTP, the cookie will not be set.
Make sure you are either using HTTPS (always in production!) or you set cookie.secure to false (maybe, and for development only!)
The secure flag in cookies
The secure flag is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure flag is to prevent cookies from being observed by unauthorized parties due to the transmission of a the cookie in clear text.
To accomplish this goal, browsers which support the secure flag will only send cookies with the secure flag when the request is going to a HTTPS page. Said in another way, the browser will not send a cookie with the secure flag set over an unencrypted HTTP request.
By setting the secure flag, the browser will prevent the transmission of a cookie over an unencrypted channel.
from https://www.owasp.org/index.php/SecureFlag
Cookies in express-session
Following common practice, express-session uses cookies to store a session ID and server side storage (mongoDB in your case) to store session data. If the browser does not send your session ID because it can't find a valid cookie, your server will assume there is no session, and save the user id on a new session on every request.
When you got to /authentication it will save the ID on a new session. When you try to read in in a different request, the session ID has changed and you have no value in userID.