NodeJS express-session, if cookie path is set, cookie doesn't save - express

I have a web page with passport login and express session.
Everything works but the cookie and I noticed what was the problem ( if I define the path of the cookie, the cookie doesn't add to the domain. )
If anyone knows why it happens please tell me.
(session store: connect-mongo 4.6.0)
app.use(session({
secret: 'secret',
store: Store.create({
mongoUrl: 'myMongoURL',
dbName: 'db-sessions'
}),
cookie: {
path: '/menu',
domain: 'mydomain.com',
maxAge: 60000 * 60 * 24,
},
resave: false,
saveUninitialized: false,
}))

When you add a path to the cookie, that cookie will ONLY be sent to the server for a request to that specific path.
So, only a request for the /menu path sent to your server will include that specific cookie. A request to your server for any other path will not include that cookie. The client is only sending the cookie with requests that match that specific path.
Note that a path in the cookie of /menu will match a request to /menu and also /menu/somethingelse.

Related

cookie cannot be set due to user preference - withCredentials true, CORS set up

response cookie screenshot
response header
My site is able to save cookies if the frontend and backend are localhost:3000 talking to localhost:4000, but once I deploy them, it's no longer saving the cookies.
I am using Axios and Express to handle the http requests.
Frontend:
const axiosConfig = axios.create({
baseURL: process.env.REACT_APP_baseURL || "http://localhost:4000" ,
withCredentials: true
});
Backend cookie sending:
const token = jwt.sign(
{
user: existingUser._id,
sciper: input_sciper,
role: role
},
process.env.JWT_SECRET,
{ expiresIn: '1d' }
)
console.log("path /login correct")
res.cookie("token", token, {
httpOnly: true,
secure: true,
sameSite: "None"
}).send()
Express setup:
app.use(cors({
origin: [
"http://192.168.43.169:3000",
"http://localhost:3000",
"https://epfl-course-rank.herokuapp.com",
"https://www.coursefinder.ch"
],
credentials: true,
}));
The screenshot says that the cookie is sent, as it's in the response header, but not set by chrome (nor any other browser). If I hover over the yellow "!" button, it says "the set cookie is blocked because user preferences."
So if I change my cookie preferences to allow all cookies, my site works -- it still doesn't save cookie into Applications but at least it logs in and sends with requests.
I know there are lots of questions asked on CORS/Cookie setting already, but I am still lost after reading through dozens of them.
I set the credentials, the requests are sent with credentials as well.
It's also really bizarre that when I set my chrome setting to "allow all cookies", then my site works. Does this mean that chrome considers my cookie as third party instead of first-party?
Any help /explanations would be greatly appreciated.

Unable to use session cookie in server-side request (getServerSideProps) in Next.js

I'm trying to perform a request to a backend service using Axios inside getServerSideProps, but it is failing because the session cookie that is needed for authentication is not included in context.req headers.
The application has its client on a subdomain (e.g. app.domain.com) and the backend service, which is based on Node/Express.js, is on another subdomain (e.g. api.domain.com). The cookie is being sent during authentication and seems to be correctly stored in the browser, but interestingly, it is not stored within the client subdomain, but as part of the backend subdomain (api.domain.com).
I'm using cookie-session for handling the response from Express with the following config flags:
app.use(
cookieSession({
signed: false,
secure: true,
httpOnly: true,
sameSite: "strict"
})
);
I've played with the cookie-session middleware config flags, setting sameSite to "none" and httpOnly to false, with no success. I've also checked the contents of the "context" object in getServerSideProps, just to confirm that the cookie is not being sent to the server.
Assuming you have correctly configured a middleware in your backend to send/accept credentials and accept CORS requests (e.g. https://expressjs.com/en/resources/middleware/cors.html), you can try to add the "domain" flag to cookieSession options.
app.use(
cookieSession({
signed: false,
domain: "your-domain.com",
secure: true,
httpOnly: true,
sameSite: "strict"
})
);
This way, the cookie will be stored in the "domain scope" and not restricted to your backend subdomain.

Apollo graphql application cookie not set in browser

I am using apollo graphql on backend side and using cookie authentication method. But when I set cookie on backend side cookie was in Set-Cookie header but doesn't showed in Browser->application ->cookies
response.cookie('tokens', token, {
httpOnly: true,
secure: true, //process.env.NODE_ENV === 'production',
sameSite: true,
expires: new Date(Date.now() + 1000 * 60 * 60 * 24),
});
Returned response:
Response image
Nothing here.
Application cookies
Tried many advices but nothing worked for me.
You can set the cookie by
context.setCookies.push({
name: "token",
value: result.token,
options: {
domain:'DOMAIN_NAME',
httpOnly: true,
maxAge: 36000,
secure: 'none',
path: '/',
sameSite:'None'
}
});
Remember to make sure domain name is your Server host name,
no need of protocol in domain, i.e., https
set samesite to none
by this, I was able to set the cookie and it was set in application folder in developers tool
you cannot test this in incognito,
in network tab, in the rest call, in cookie section, you can confirm if all attribute is set correct or not.

express-session cookies blocked in browsers

I know this question is redundant, but I have been searching and reading articles all around for hours now. I am using express-session to control user sessions for the express server. It works when I try to console req.session.user from a postman request. When I try to fire the same request from the browser, it returns undefined. Everyone is talking about Chrome security updates and third-party cookies restrictions. I've tried to stick to chrome guidelines on cookie options but didn't help. If I deployed my client or server to a secure domain would it help?
Here are my options
app.use(cors())
app.set('trust proxy', 1) // trust first proxy
app.use(session({
store: new (require('connect-pg-simple')(session))({pool}),
secret: process.env.SESSION_SECRET,
resave: true,
rolling: true,
cookie: {
maxAge: 30 * 60 * 1000, // 30 minutes
secure: false,
sameSite: 'none'
},
saveUninitialized: false,
}));

How to save persistent data in Express?

I have a simple requirement to store an access token/refresh token in Express (without using localStorage or anything). I'd like to store them in a persistent httpOnly cookie so any time a user visits the page who has previously visited the page can see if the access token is already there, and if so, make API calls and log in and so on.
I've spend some time looking at express-session and cookie-session and simply can't figure out the proper way to do it. express-session requires a store for production, and I don't want to set up a store to simply store an access token. So something like this works in devleopment:
app.use(
session({
secret: 'conduit',
cookie: {
path: '/',
maxAge: 60 * 60 * 1000,
httpOnly: true,
secure: isProduction,
},
resave: false,
saveUninitialized: false,
})
)
Using this to set it on request:
request.session.accessToken = accessToken
request.session.save()
But if it's not going to work in a production environment, it's not helpful. I haven't been able to get it working with cookie-session, or I don't know how to set/retrieve the cookies, and the documentation isn't very helpful.
So I'm asking: how can I store a few strings on an Express server/httpOnly cookie in a persistent way, without using a Store/Redis/MemCache/etc?
I had to use cookieParser.
const cookieParser = require('cookie-parser')
app.use(cookieParser())
// set a cookie
response.cookie('nameOfCookie', 'cookieValue', {
maxAge: 60 * 60 * 1000, // 1 hour
httpOnly: true,
secure: isProduction,
})
// get a cookie
request.cookies.nameOfCookie
// destroy cookie
response.clearCookie('nameOfCookie')