Node serving session cookies instead of using maxAge - node.js

I am using code from Stripe's rocket rides to serve cookies and remember users:
const cookieParser = require('cookie-parser');
const session = require('cookie-session');
// ...
const app = express();
// Enable sessions using encrypted cookies
app.use(cookieParser(config.secret));
app.use(
session({
// cookie expiration: 90 days
cookie: {maxAge: 90 * 24 * 60 * 60 * 1000},
secret: config.secret,
signed: true,
resave: true,
})
);
The problem is that the cookies served are session cookies (I inspected them with Chromium Developer Tools) and deleted when the browser window closes. I checked that the live server of Rocket Rides also serves session cookies.
How can I enforce the maxAge for the cookie to persist for 90 days?

Here try this.
app.use(cookieParser(config.secret));
app.use(
session({
// Cookie Options
maxAge: 90 * 24 * 60 * 60 * 1000,
secret: config.secret,
signed: true,
resave: true,
})
);

Related

Can't set cookie from subdomain1.example.com which can be read by example.com

I'm using the following to configure my session on subdomain1.example.com:
const expressInstance = express();
expressInstance.use(
session({
secret: "my secret",
cookie: {
domain: '.example.com',
sameSite: 'none',
secure: true,
maxAge: 1000 * 60 * 60 * 48
}
})
);
expressInstance.set('trust proxy', 1);
Then I set it as:
res.cookie("cookie_name", "cookie_value")
I can see this cookie when I visit subdomain1.example.com but not when I visit example.com.
What am I missing? Isn't this a very common use case?

is there a way to identify session problem?

I use express-session with oauth library, but it seams there is some problem to save session data while interacting with oauth server
is there a way to identify possible session-saving problem?
I init a session in such way
app.set("trust proxy", 1)
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie:
{
secure: false, httpOnly:false,
sameSite: false,
maxAge: 30 * 24 * 60 * 60 * 1000,
}
}));
i try to debug code, but don't a source of problem

NodeJS / express session timing out early

In my NodeJs / Express app, I'm using the standard session package and Passport to handle sessions and login. My problem is that the app kicks the user out after what feels like 10 minutes of inactiviy, and forces them to log-in again. My assumption is that it must be something to do with the session configuration, which with my limited understanding, I think is configured to allow 2 hours:
const session = require("express-session");
const PostgreSqlStore = require("connect-pg-simple")(session);
const sessionAge = 2 * 60 * 60 * 1000; // hour, min, sec, millisecond
var sessionConfig = {
name: "mysite",
secret: "verysecret",
resave: true,
saveUninitialized: false,
proxy: trustedTypes,
cookie: {
key: "cookieKey",
secure: true,
sameSite: false,
httpOnly: true,
maxAge: sessionAge,
},
store: new PostgreSqlStore({
pgPromise: db,
ttl: 2 * 60 * 60, //Hours, minute, seconds
}),
};
app.use(session(sessionConfig));
Is there anything I'm doing wrong, or is there something else I should be looking at to find the cause of this behavior?
store: new PostgreSqlStore({
pgPromise: db,
ttl: 2 * 60 * 60, //Hours, minute, seconds
})
I think your PostgreSQL store ttl property should be equivalent to maxAge property of session config
I've discovered that apparently although by default the session does get extended on the server, it won't send an updated cookie to the browser if nothing has changed in it. The missing property is the 'rolling' attribute.
var sessionConfig = {
rolling: true,

I can't set the SameSite attribute of the cookie to None in Nodejs (Express)

We are creating a backend for a Twitter view app in Nodejs (Express).
I'm thinking of using Twitter Api for login and storing the token returned after authentication to the session and then restoring the session from the cookie when it is accessed again.
However, the cookie is blocked when it is accessed again and I can't restore the session information.
The browser I use is chrome, but since chrome version 80, SameSite attribute seems to be Lax (sends a cookie when called from the site of the same domain) when the SameSite attribute is not specified, and in this case, front and back end are different domains, so cookies are blocked.
So I am trying to set the SameSite attribute to None (sends a cookie when called by any site), but I can't seem to set it well and asked this question.
I'm wondering if I can set the SameSite attribute to None if I make a difference in the part of app.use(session({})), but...
If anyone knows of a solution, I would appreciate your help.
Thank you for your help.
The corresponding source code
callback_url = env.URL + "oauth/callback";
app.use(
cookieSession({
name: "session",
keys: ["thisappisawesome"],
maxAge: 24 * 60 * 60 * 100
})
);
app.use(cookieParser());
// Save to session
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// Restore from Session
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(
new TwitterStrategy({
consumerKey: env.TWITTER_CONSUMER_KEY,
consumerSecret: env.TWITTER_CONSUMER_SECRET,
callbackURL: callback_url
},
async (token, tokenSecret, profile, done) => {
return done(null, profile);
}
));
app.use(session({
allowedHeaders: ['sessionId', 'Content-Type'],
exposedHeaders: ['sessionId'],
secret: 'reply-analyzer',
resave: false,
saveUninitialized: false
}));
var cors_set = {
origin: env.CORS_ORIGIN_URL,
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true // allow session cookie from browser to pass through
};
app.use(passport.initialize());
app.use(passport.session());
app.use(cors(cors_set));
What I've tried.
1.I tried setting the cookie options in the app.use(session({})) part, but it was not possible to set the SameSite attribute to None.
app.use(session({
allowedHeaders: ['sessionId', 'Content-Type'],
exposedHeaders: ['sessionId'],
secret: 'reply-analyzer',
resave: false,
saveUninitialized: false,
cookie : {
secure: true,
sameSite: 'None'
}
}));
2.I tried using the following middleware (express-samesite-default), but the SameSite attribute can be set to None, and the It wasn't.
var sameSiteCookieMiddleware = require("express-samesite-default");
app.use(sameSiteCookieMiddleware.sameSiteCookieMiddleware());
Additional information
Node.js v12.18.2
chrome v84.0.4147.135
I was able to self-resolve and will describe how I was able to solve the problem.
In the code there are two sessions and a cookie session, but I decided to use the cookie session as it seems to work fine.
The end result is the following
var cookieSession = require("cookie-session");
app.set('trust proxy', 1)
app.use(
cookieSession({
name: "__session",
keys: ["key1"],
maxAge: 24 * 60 * 60 * 100,
secure: true,
httpOnly: true,
sameSite: 'none'
})
);
Hey I just used like this. And it worked. I'm using localhost for both frontend and express backend.
res.cookie('token', token, {
expires: new Date(Date.now() + (3600 * 1000 * 24 * 180 * 1)),
httpOnly: true,
sameSite: "none",
secure: "false",
});
try SameSite: 'none' with capital S it worked for me but i used express-session with cookie-parser... i think your code not working because of small s, when i change my to sameSite it's not working for me too, but SameSite works just as expected
also i use npm i cors
here is my piece of code
app.use(session({
key: 'session_cookie_user_auth',
secret: 'mooncore',
store: sessionStore,
resave: false,
saveUninitialized: false,
cookie: {
SameSite: 'none',
maxAge: 1000 * 60 * 60 * 60
}
}));

Why is my session expiring every time I close the browser?

I set up the session maxAge of express like documented.
Here is my code:
app.use(session({
secret: process.env.SESSION_SECRET,
saveUninitialized: true,
resave: true,
maxAge: 1000* 60 * 60 *24 * 365,
store: new MongoStore({mongooseConnection:mongoose.connection})
}));
But every time I close the browser, I find myself logged out.
Also, note that I am using Passport local, facebook, and google authentications.
They all expire.
In the console, I can see that the connect.sid in the expires/maxAge section lists "Session" while other cookies have dates...
What am I doing wrong?
you need to configure your express-session, and set maxAge on session-cookie
app.use(express.session({
cookie : {
maxAge: 1000* 60 * 60 *24 * 365
},
store : new MongoStore({mongooseConnection:mongoose.connection})
});
//.....
app.use(passport.session());

Resources