Nodejs/Express/Cookies: how do you set signed cookies with a secret - node.js

In my directory i have app.js And Index.htmml ; I am trying to set cookies from App.js; I have tried:-
var express = require('express'),
app = express(),
http = require('http'),
cookieparser = require ('cookie-parser'),
httpServer = http.Server(app);
app.use(express.static(__dirname + '/data'));
app.get('/', function(req, res) {
let options = {
maxAge: 60000, // would expire after 1 minutes
httpOnly: true,
signed: true ,
secret: 'secret'
}
// Set cookie
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
res.cookie('cookieName', 'Success', options)
res.sendFile(__dirname + '/index.html');
});
app.listen(8080);
When i run app.js from Cmd It dissappoints me with this error
Thanks in advance for help
Error: cookieParser("secret") required for signed cookies

You need to specify a secret key which will be used while signing the cookie.
You can do this by adding the following line to your code.
app.use(cookieparser("secret"));

According to the snippet, you are using the express-session module like so:
app.use(require('express-session')({ secret: 'keyboard cat', ... }));
That is already saying that you want cookies to be signed. Therefore, in your cookie options you can remove the option signed: true since it will be redundant.
And on a last note, you need to improve that code.

Related

Res header contaisn set Cookie but browser isn't storing it

I'm using express-session to store session cookie. I can see Set-Cookie connect.ssid under the response header but for some reason it is not getting stored in the cookie.
I'm wondering if this is a CORS issue, my app file looks like this. Should I change something here to make it work.
const session = require('express-session');
const config = require('config');
var MemoryStore = require('memorystore')(session);
module.exports = function (app) {
// app.use(
// session({
// secret: 'key sign',
// resave: false,
// saveUninitialized: false
// })
// );
app.use(express.json());
app.use(cors({ credentials: true }));
enter code here
app.set('trust proxy', 1);
app.use(
session({
saveUninitialized: false,
cookie: { maxAge: 86400000 },
store: new MemoryStore({
checkPeriod: 86400000
}),
resave: false,
cookie: { secure: false },
secret: config.get('sessionStorage')
})
);
app.use('/api/users', users);
Here is how I fixed this.
Add SSL to both frontend and backend.
If it is self-signed, ensure browser trust it. For example, if you're using mac, go to keychain, select specific certificate and select always trust option.
Restart the system. Only then SSL will be properly set otherwise there would still be insecure badge in the navigations.

Express session don't persist

I was making a React project, and I was using Express for backend. I set http://mini-api.moonlab.ga as a virtual host for Express server.
I sent a HTTP Request to express server with Fetch:
fetch("http://mini-api.moonlab.ga/login/", {
credentials: "include"
})
and as I expected there was a CORS error. So I installed cors package, and I set code like this in Node.js:
app.use(cors({
origin: true,
credential: true
}));
And I respond to client from server like this:
app.get("/login", (req, res) => {
const session = req.session;
if (session.miniAccount == undefined) {
session.miniAccount = Math.floor(Math.random() * 1000000);
}
res.writeHead(200, {"Access-Control-Allow-Credentials": true});
res.write(String(session.miniAccount));
res.end();
})
After I did like this, there wasn't any CORS error, but the session don't persist. When I send a request again, the session data keeps changes.
Well how to make session persist?
Server's session code:
app.use(express_session({
secret: secret.app_key,
resave: false,
saveUninitialized: true
}));
You may try setting a maxAge value inside cookie
...
const session = require("express-session");
...
app.use(
session({
secret: secret.app_key,
resave: false,
saveUninitialized: true
cookie: {
maxAge: 3600000 //session expires in 1 hr
}
})
);
I solved it myself by editing package.json.
I added "proxy": "mini-api.moonlab.ga" in package.json.
Than I edited fetch().
previous
fetch("http://mini-api.moonlab.ga/login")
new
fetch("/login")
And it worked.

Problem with connect.sid and session in a node.js application, in production environment

The node application uses passport-ldap for authentication, and the issue is that it works like a charm in the development environment, but the are problems in the production one. When the route is being changed, I lose the user's session because the connect.sid (the cookie) of the Application is being changed, because I have a new setCookie response.
I am using express 4.17.1 and express-session 1.16.2, so from my research I found that i do not have to use cookieParser. I also think that there is no issue with the serialize and deserialize of the user and passport functionality.
// Static folder set
app.use(express.static(path.join(__dirname, 'public')));
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('trust proxy', 1) //trust first proxy
// Express session midleware
app.use(session({
secret: 'abc',
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
...
// Use routes of the application
app.use('/users', users);
I found the solution and i post it for future reference, in case someone else faces a similar issue.
I used the cors module and set it like that
app.use(cors({credentials: true}));
also in production enviroment you have to use a store to hold the cookie. This was obvious but i missed it. So i used
const MongoStore = require('connect-mongo')(session);
app.use(session({
secret: 'abc',
resave: false,
saveUninitialized: false,
cookie: { secure: true,
maxAge: 6*60*60*1000 },
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));

Session is not defined in Express

I've included the cookie-parser before the session (not sure if needed with the current versions), imported express-session as visible. If I change session to express.session on line 8 I get a deprecation error (not warning).
var express = require('express'),
cookieParser = require('cookie-parser'),
expressSession = require('express-session'),
port = process.env.PORT || 3000;
app = express();
app.use(cookieParser());
app.use(session({
secret: "yadayada",
resave: true,
saveUninitialized: true
}));
app.get('/', function (req, res) {
console.log(req.session);
console.log(req.cookies);
});
app.listen(port);
session is not defined on line 9 because you have it declared as expressSession at the top i.e.
expressSession = require('express-session')
Either rename the declaration to session or update line 9 to call expressSession i.e.
app.use(expressSession({ ... }));
same question......
but https://github.com/expressjs/session?_ga=1.45435812.1066105876.1451139756
app.use(session({
genid: function(req) {
return genuuid() // use UUIDs for session IDs
},
secret: 'keyboard cat'
}))

req.user undefined in Express 4

I built an app that uses Oauth to authenticate with a third party Jawbone app. I'm attempting to pull req.user.jawbone.token from req.user in one of my routes; however, I'm getting an error stating that req.user is undefined. I had this working in express 3, but after upgrading to express 4 it's no longer working - which leads me to believe that my sessions aren't being stored properly.
Here are the relevant parts of my app.js configuration:
var passport = require('passport');
var session = require('express-session')
var MongoStore = require('connect-mongo')({session: session});
require('./config/passport')(passport);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// passport
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(session({
store: new MongoStore({
url: mongoUrl
}),
secret: 'password',
resave: false,
saveUninitialized: true
}));
For anyone else that runs into this problem, the issue was due to my middleware being in the wrong order. I rearranged to the below and it's working properly
app.use(session({
store: new MongoStore({
url: mongoUrl
}),
secret: 'password',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

Resources