can console.log content of signedCookie but can not access content - express

Have an express backend that sent signedCookies. the content of the signedCookie is a key and an object with 2 JWT as value
"tokens": "{
"accessToken":"klkmlk",
"refreshToken":"kjlkjkle"
}"
When client is sending back the cookie, I can console log the "tokens", that shows the object, but for example tokens.accessToken returns undefined...
What's wrong ?
// parser with the secret jey to sign the cookie
app.use(cookieParser("secretKeyForCookie"));
// signed cookie options
res.cookie("tokens", checkLogin.data, {
httpOnly: true,
secure: true,
signed: true,
maxAge: 100000,
sameSite: true,
path: "/",
});
//, Object.keys lists keys but undefined when access one of the key
console.log(
Object.keys(req.signedCookies.tokens), // returns ['accessToken', 'refreshToken']
req.cookies.tokens["accessToken"] // undefined
);

Related

Set-Cookie with sameSite=none and secure = true

I am having a project with frontend and expressjs backend, both are hosted in Vercel.
I am facing a problem with setting cookies,
if I am using
app.use(
cookieSession({
name: "portfolio-cookie-session",
secret: process.env.COOKIE_SECRET, //secret environment variable
httpOnly: true,
expires: getExpire(), //return date
sameSite: "none",
secure: true,
})
);
my frontend couldn't get any set-Cookies header,
browserheader-image
if I remove samesite and secure
app.use(
cookieSession({
name: "portfolio-cookie-session",
secret: process.env.COOKIE_SECRET, //secret environment variable
httpOnly: true,
expires: getExpire(), //return date
// sameSite: "none", <---remove
// secure: true, <---remove
})
);
then browser can show the cookie header however, it will blocked cause samesite problem
browserheader-image
warning-image
Thank you!

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 not saving/persisting over https using azure app services

I've looked through quite a few issues on this and have tried every combination of "solutions" for my problem but can't seem to figure this one out.
I currently have a client side react application being hosted on azure. Let's call this https://clientside.net for short.
I also have a server side node js application being hosted on azure we'll call this https://serverside.net.
I can't seem to to get the session variables to save upon authenticating users. This works perfectly fine on localhost btw.
e.g. On the client side we are making requests using axios like so:
const headers = {
withCredentials: true,
headers: { auth: process.env.REACT_APP_SECRET },
};
axios.get(`${process.env.REACT_APP_SERVER}/get/auth`, headers).then((response) => console.log("blah blah blah"));
On the server side this is how express session is setup...
app.use(
cors({
origin: ["https://clientside.net"],
methods: ["GET", "POST"],
credentials: true,
})
);
app.set("trust proxy", 1);
app.use(
session({
name: "sid",
saveUninitialized: false,
resave: false,
secret: "shhh",
cookie: {
domain: ".clientside.net",
maxAge: 1000 * 60 * 60 * 8,
secure: true,
httpOnly: false,
},
})
);
Within our authentication route on server side we are saving session like so ...
req.session.username = req.body.username;
req.session.password = req.body.password;
req.session.save(() =>
res
.status(202)
.json({
authenticated: true, username: req.session.username})
);
Upon refreshing or attempting to hit any other routes, the req.session.username & req.session.password are nowhere to be found. Is there something wrong with my session config? Or am I perhaps missing something? I appreciate any and all help on this! Thanks y'all
I've figure out the issue.
Deploying an application using azure app services, means you will be using a reverse proxy.
In my case nodeiis web service proxy.
The client side makes requests to the iis service which then routes the request to the node server.
I made many changes but the one that got me up and running was switching the cors origin and session domain to be the server side domain/ip like so...
app.use(
cors({
origin: ["https://serverside.net"],
methods: ["GET", "POST"],
credentials: true,
})
);
app.set("trust proxy", 1);
app.use(
session({
name: "sid",
saveUninitialized: false,
resave: false,
secret: "shhh",
cookie: {
domain: ".serverside.net",
maxAge: 1000 * 60 * 60 * 8,
secure: true,
httpOnly: false,
},
})
);
Now session variables are able to be successfully saved upon login.

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')

how do I can generate sessions in server for logged in users only , with Express, Express-session, Passport and Connect-mongo?

I'm using express-session, passport, connect-mongo and mongodb-atlas last versions, for create sessions and save them on the server, the
problem is when app.use(passport.session()), this session is created even if the user is not logged in.
app.use(session({
// key: "id",
secret: process.env.SESSION_SECRET,
cookie: {
httpOnly: true,
sameSite: true,
// secure: process.env.IN_PROD,
maxAge: 10800000,
}, // three hours in miliseconds
store: new MongoStore({
mongooseConnection: mongoose.connection,
autoReconnect: true,
collection: "admin.mySessions",
serialize: serialize
}),
resave: false,
saveUninitialized: false,
name: 'Id'
}));
this causes that when passport is initialized and the passport session
the cookie is saved with session id and the session is saved in the
mongodb
mi question is how save session only for users logged in
Hello mate I am not aware of mongo-session, but from your explanation I understand that you are creating token for users even if they don't login. I suggest you create a new token each time a user hits login API and expire the token once he logs out.By following this token is generated only for active users.