req.user undefined in Express 4 - node.js

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());

Related

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 })
}));

Nodejs/Express/Cookies: how do you set signed cookies with a secret

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.

Redis not working on express-session

The code below is quite a normally snippet, but it's not working, session from request is undefined. Anyone who can give me a hint will be appreciated.
var express = require('express');
var session = require('express-session');
var redisStore = require('connect-redis')(session);
var app = express();
app.listen(3000);
app.use(session({
store: new redisStore({
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
app.get('/', function (req, res) {
if(req.session.isVisit) {
req.session.isVisit++;
res.send('<p>times to be here:' + req.session.isVisit + '</p>');
} else {
req.session.isVisit = 1;
res.send('1st time to be here');
}
});
A Redis client is required
var redis = require("redis"); // You can use any module to create redis client
app.use(session({
store: new redisStore({
client : redis.createClient(<your setting>)
host:'localhost',
port:'8543'
}),
resave: false,
saveUninitialized: true,
secret: 'somesecrettoken'
}));
Please refer this link:
https://www.npmjs.com/package/connect-redis
Pass the express-session store into connect-redis to create a RedisStore constructor.
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore(options),
secret: 'keyboard cat'
}));

getting authenticated user info from passportjs and express

I have an express application that uses passport for OAuth. I have it working successfully with Google and Facebook. My problem is that I can get req.user on controller functions where the routes are configured like this:
router.post('/', auth.isAuthenticated(), controller.create);
but when I try to access the user info from a controller function that doesn't require authentication, req.user is undefined even though the user is logged in. What am I doing wrong here?
and here is how express and passport are configured:
module.exports = function(app) {
var env = app.get('env');
app.set('views', config.root + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
// Persist sessions with mongoStore
// We need to enable sessions for passport twitter because its an oauth 1.0 strategy
app.use(session({
secret: config.secrets.session,
resave: true,
saveUninitialized: true,
store: new mongoStore({ mongoose_connection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());
.
.
.

mongoose.connect giving error in nodejs

I am using node to connect to mongoose database, but when i run the code, it gives error as:
Uncaught TypeError: undefined is not a function
(anonymous function) server.js:13
Below is the code which i am running in server.js
var express= require(['express']);
var bodyParser = require(['body-parser']);
var cookieParser = require(['cookie-parser']);
var expressSession = require(['express-session']);
var mongoose = require(['mongoose']);
var mongoStore = require(['connect-mongo'])({session: expressSession});
require(['./models/users.js']);
mongoose.connect('mongodb://localhost/userregistration');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views',__dirname + '/views');
app.set('view engine','html');
app.use(bodyParser());
app.use(cookieParser());
app.use(expressSession({
secret: 'SECRET',
cookie: {maxAge:60*60*1000 },
store: new mongoStore({
db: mongoose.connection.db,
collection: 'sessions'
})
}));
require('./routes')(app);
app.listen(80);
looking at the logs, the code is giving the error at:
mongoose.connect('mongodb://localhost/userregistration');
I think you forgot to require express-session.
Here is the example
ExpressSession
app.use(express.session({
secret: 'SECRET',
cookie: {maxAge:60*60*1000 },
store: new mongoStore({
db: mongoose.connection.db,
collection: 'sessions'
})
}));
connect-mongo has a special option for using Mongoose connections, try using that:
store: new mongoStore({
mongoose_connection: mongoose.connection,
collection: 'sessions'
})
If that doesn't fix it, please post more information (like a full stack trace and the actual code you're running, since those require's don't look right).
// Replace 'db' by 'mongooseConnection '
app.use(expressSession({
secret: 'SECRET',
cookie: {maxAge: 60 * 60 * 1000},
store: new mongoStore({
mongooseConnection: mongoose.connection,
collection: 'sessions'
})
}));

Resources