The session of my nodejs app is expiring every time I refresh the page, after login. It does work fine if I visit different pages but as soon as I refresh the page, the session ends. I've tried a couple of things but none of it seems to work. How can I keep it from expiring even after the page refresh? If I can store session in the database or someplace else to keep it from expiring.
Here are the files
Passport-init.js
var mongoose = require('mongoose');
var User = mongoose.model('user');
var localStrategy = require('passport-local').Strategy;
var bcrypt = require('bcrypt-nodejs');
module.exports = function(passport) {
passport.serializeUser(function(user, done) {
console.log('serializing user:',user.username);
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
if(err) {
done(500,err);
}
console.log('deserializing user:',user.username);
done(err, user);
});
});
passport.use('login', new localStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
User.findOne({'username': username},
function(err, user) {
if(err) {
return done(err);
}
if(!user) {
console.log("UserName or Password Incorrect");
return done(null, false);
}
if(!isValidPassword(user, password)) {
console.log("UserName or Password is Incorrect");
return done(null, false);
}
return done(null, user);
});
}));
passport.use('signup', new localStrategy({
passReqToCallback : true
}, function(req, username, password, done) {
User.findOne({'username': username},
function(err, user) {
if(err) {
console.log("Error in signup");
return done(err);
}
if(user) {
console.log("Username already exist" + username);
return(null, false);
}
else {
var newUser = new User();
newUser.username = username;
newUser.password = createHash(password);
newUser.save(function(err) {
if(err) {
console.log("Error in saving user");
throw err;
}
console.log(newUser.username + ' Registration succesful');
return done(null, newUser);
});
}
});
}));
var isValidPassword = function(user, password) {
return bcrypt.compareSync(password, user.password);
}
var createHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(10), null);
}
};
Auth.js
var express = require('express');
var router = express.Router();
module.exports = function(passport) {
router.get('/success', function(req, res) {
res.send({state: 'success', user: req.user ? req.user : null});
});
router.get('/failure', function(req, res) {
res.send({state: 'failure', user: null, message: 'Invalid Username or Password'});
});
router.post('/login', passport.authenticate('login', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
};
Server.js
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var logger = require('morgan');
var passport = require('passport');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(session);
mongoose.connect("mongodb://localhost:27017/scriptknackData");
require('./models/model');
var api = require('./routes/api');
var auth = require('./routes/auth')(passport);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
app.use(session({
secret: 'super secret key',
resave: true,
cookie: { maxAge: 60000 },
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
var initpassport = require('./passport-init');
initpassport(passport);
app.use('/api', api);
app.use('/auth', auth);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var port = process.env.PORT || 3000;
server.listen(port, function() {
console.log("connected");
});
As per express-session documentation
cookie.maxAge
Specifies the number (in milliseconds) to use when calculating the Expires Set-Cookie attribute. This is done by taking the current server time and adding maxAge milliseconds to the value to calculate an Expires datetime. By default, no maximum age is set.
And use express.session() before passport.session() to ensure login session is stored in correct order. passport docs
In your case you have specified maxAge as 60000ms (60sec) only. Try this:
...
app.use(session({
secret: 'super secret key',
resave: true,
cookie: { maxAge: 8*60*60*1000 }, // 8 hours
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());
...
Increase your cookie maxAge value according to your need, it will solve your issue.
I was facing the same issue as you and I got the problem fixed by doing this:
If anyone is having issues, this could probably help to solve it.
app.use(session({
secret: "our-passport-local-strategy-app",
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 24 * 60 * 60 * 1000
},
store: new MongoStore({
mongooseConnection: mongoose.connection,
ttl: 24 * 60 * 60 // Keeps session open for 1 day
})
}));
I had this problem and I found out how to fix it. In my case, this problem was just during using localhost during running react app on own port. I use the build production version, there was no problem. But it is not good to run build every time you need to see changes.
First I run Nodejs on 5000 port at localhost.
In React's package.json, I added "proxy": "http://localhost:5000/". After that, I ran react app on port 3000. Now when I use fetch, the URL to my API is not http://localhost:5000/api/login but just /api/login.
You can read more about that here:
https://create-react-app.dev/docs/proxying-api-requests-in-development/
Do not forget to remove the proxy from package.json when you will deploy to the server. This is good only for the development version.
As per the fine manual (emphasis mine):
Note that enabling session support is entirely optional, though it is recommended for most applications. If enabled, be sure to use express.session() before passport.session() to ensure that the login session is restored in the correct order.
In your case, the order is not correct. Try this:
...
app.use(session({
secret: 'super secret key',
resave: true,
cookie: { maxAge: 60000 },
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection })
}));
app.use(passport.initialize());
app.use(passport.session());
...
Related
Original Question
I am using passport.js to do authentication in express, when I use req.flash('message', 'message content') in passport strategy, the flashed information is not under the normal session but 'sessions' and when I tried to retrieve the flashed message using req.flash(), it's an empty array.
I printed out the req
, it looks like this:
MemoryStore {
_events:
{ disconnect: [Function: ondisconnect],
connect: [Function: onconnect] },
_eventsCount: 2,
_maxListeners: undefined,
sessions:
{ gzNcx9b8rcWfDtJm03VnNJfhsNW8EJ7B:
'{"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"flash":{"message":["emails has been taken, choose another one!"]}}' },
generate: [Function] },
sessionID: 'ffSa89VCV0Mj6uKLrEPMAdNMGLR2I5ML',
session:
Session {
cookie:
{ path: '/',
_expires: null,
originalMaxAge: null,
httpOnly: true } },
_passport:
Somehow it opens a new session after redirecting to /api/signupFail. Could anyone help me with this?
Here is my middleware setup:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var passport = require('passport');
require('./config/passport')(passport);
var cors = require('cors');
var session = require('express-session');
var flash = require('connect-flash');
var app = express();
var corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
app.use(logger('dev'));
app.use(cookieParser('Thespywhodumpedme'));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
var goalsRoute = require('./routes/goalsRoute');
var userRoute = require('./routes/userRoute');
// required for passport
app.use(flash());
app.use(session({ secret: 'keyboard cat',resave: true, saveUninitialized:true})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
// use connect-flash for flash messages stored in session
app.use(express.static(path.join(__dirname, 'public')));
app.post('/api/signup', passport.authenticate('local-signup', {
successRedirect: '/api/user/suctest',
failureRedirect: '/api/signupFail',
failureFlash: true
}));
app.get('/api/signupFail', (req, res, next) => {
console.log(req.flash('message')); //this is an empty array
res.status(403).send('fail');
})
Here is my strategy setup:
module.exports = function(passport) {
passport.serializeUser((user, done) => {
done(null, user.id);
});
// used to deserialize the user
passport.deserializeUser((id, done) => {
db.User.getUserById(id, (err, result) => {
done(err, result[0]);
});
});
passport.use('local-signup', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true // allows us to pass back the entire request to the callback
},
function(req, email, password, done) {
if(!email || !password ) { return done(null, false, req.flash('message','All fields are required.')); }
var salt = '7fa73b47df808d36c5fe328546ddef8b9011b2c6';
db.User.getUserByEmail(email, function(err, rows){
if (err) {
return done(req.flash('message',err));
}
if(rows.length > 0){
return done(null, false, req.flash('message',"emails has been taken, choose another!"));
}
salt = salt+''+password;
var encPassword = crypto.createHash('sha1').update(salt).digest('hex');
var newUser = {
name: req.body.name,
email: email,
password: encPassword,
sign_up_time: new Date()
}
db.User.addOneUser(newUser, (err, result) => {
db.User.getUserByEmail(email, (err, result) => {
return done(err, result[0]);
})
});
});
}));
};
Update
At first, I thought it has something to do with flash, but then after printing session out, I found that a new session is created after redirecting. I thought it has something to do with the backend setup. Accidentally, I found this problem doesn't exist when I sent the request from postman. That's when I figured out it might have something to do with Angular which is listening on port 4200 while express listening on port 3000. I was sending the request to port 3000 by hardcoding the port number in httpClient. After I set up a proxy that redirects all API call to port 3000. Everything works just fine.
OK, it turns out that it has nothing to do with the backend. Everything works just fine when I sent the request through postman. The problem is with the frontend, I am using Angular 6, Angular is listening on port 4200 while express listening on port 3000. I set up a proxy in Angular that redirects all API call to localhost: 3000 and the session is persistent.
I hava a simple auth panel with bookshelf and passport, but when i try log in i get white empty page 500. I try all solutions which i found in web. Please help.
config/passport.js
...
passport.use('local-login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
User.where({username: username}).fetch().then(function(err, user) {
if (err) return done(err);
if (!user) {
return done(null, false, req.flash('loginMessage', 'Cant find user!'));
}
user = user.toJSON();
if(User.validPassword(password, user.password)){
return done(null, false, req.flash('loginMessage', 'Invalid pass!'));
}
return done(null, user);
}).catch(function(err) {
console.error(err);
});
}
));
...
routes/auth.js
...
router.post('/login', passport.authenticate('local-login', {
successRedirect: '/users/profile',
failureRedirect: '/auth/login',
failureFlash: true
}));
...
server.js
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const flash = require('connect-flash');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const config = require('./config/app.js');
const index = require('./routes/index');
const auth = require('./routes/auth');
const users = require('./routes/users');
require('./config/passport.js')(passport);
const app = express();
app.set('env', config.website.env);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')))
app.use(session({
secret: config.security.salt,
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use('/', index);
app.use('/auth', auth);
...
I think the major issue here is in the use of then(). It does not take an err argument as traditional callbacks.
Another minor issue is that the catch() should forward the error to passport instead of just logging it.
So try changing it to something like
passport.use('local-login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
new User({username: username})
.fetch()
.then(function(user) {
if (!user) {
return done(null, false,
req.flash('loginMessage', 'Cant find user!'));
}
user = user.toJSON();
if (User.validPassword(password, user.password)) {
return done(null, false,
req.flash('loginMessage', 'Invalid pass!'));
}
return done(null, user);
})
.catch(function(err) {
return done(err);
});
}
));
As a side note I was a bit confused by User.validPassword(). Does it return a true value for invalid passwords?
I'm loosely following the tutorial here, and I'm not sure why it's not working. Logging in will work fine -- it accepts and rejects me exactly how I'd expect, it will just not save the session, so visiting any links after will say that I am not authenticated.
Vivaldi dev panel says that no cookies or sessions are saved. I have set it up to save my sessions in redis and user authentication in PostgreSQL, and both databases are connected to fine.
Here is the relevant code:
index.js:
const express = require('express');
const passport = require('passport');
const session = require('express-session');
const Redis = require('ioredis');
const RedisStore = require('connect-redis')(session);
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const auth = require("./app/authenticate");
const config = require('./config');
const app = express();
var redis_client = new Redis({
host: config.redisStore.host,
port: config.redisStore.port,
lazyConnect: true
});
redis_client.connect().catch(function(err) {
throw err;
});
app.use(cookieParser(config.redisStore.secret));
app.use(session({
cookie : {
maxAge: 36000000000,
secure: true
},
secret: config.redisStore.secret,
store: new RedisStore({ client: redis_client }),
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.urlencoded({extended: true}));
auth.init.initPassport();
app.post('/login', passport.authenticate('local', {
successRedirect: '/testroute',
failureRedirect: '/'
}));
var urlencodedParser = bodyParser.urlencoded({extended: false});
app.get("/testroute", passport.authenticationMiddleware(), urlencodedParser, function(req, res) {
res.send("You are authenticated!");
});
app.listen(8080);
/app/authenticate/init.js:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const scrypt = require("scrypt");
const auth = require("./userfunctions");
const authenticationMiddleware = function() {
return function (req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.send('ERR: You are not authenticated!');
};
}
module.exports = {
initPassport: function() {
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(id, done) {
auth.getUserById(id, done);
});
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'pwd',
},
function(username, password, done) {
auth.login(username, function(err, user) {
if (err) {console.log(err); return done(err);}
if (!user) {return done(null, false);}
if (!scrypt.verifyKdfSync(user.password, password)) {return done(null, false);}
return done(null, user);
});
}
));
passport.authenticationMiddleware = authenticationMiddleware;
}
};
There are a few other files in /app/authenticate, which are index.js (just adds all the other things to modules.exports) and userfunctions.js, which just includes login and signup functions. I can post these if you need.
I have also omitted the config file, which is just database credentials for PostgreSQL and redis. Finally I have excluded test.html which is served when you GET /, and is just a test HTML login and signup form.
You can use express-session npm module to save your session value.
Below are the steps-
npm install express-session
In your startup JS file write below code
var expressSession = require('express-session');
app.use(expressSession({secret: 'yourothersecretcode', saveUninitialized: true, resave: true}));
Now you can use req.session in your code
req.session is just a json object that gets persisted by the express-session middleware, using a store of your choice e.g. Mongo or Redis.
I'm new to MEAN stack and I'm trying to setup a simple social login using google passport strategy. I can successfully authenticate myself, but when calling a redirect on success, the middle ware function isLoggedIn keeps showing req.isAuthenticated() to be false. Below are code snippets. I saw that there were multiple posts on this issue but none of the answers seem to work for me. Kindly help me resolve this issue.
passport.js
var Auth = require('./auth.js');
var ubCust = require('../models/ubCust.js');
var FacebookStrategy = require('passport-facebook').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
//var FacebookStrategy = require('passport-facebook').Strategy;
module.exports= function(passport){
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
ubCust.findById(id,function(err,user){
done(err, user);
})
});
passport.use(new GoogleStrategy ({
clientID: Auth.googleAuth.clientID,
clientSecret: Auth.googleAuth.clientSecret,
callbackURL : Auth.googleAuth.callbackURL
},
function(token, refreshToken, profile, done) {
// Create or update user, call done() when complete...
process.nextTick(function(){
ubCust.findOne({'google.id' : profile.id}, function(err, user) {
if (err)
return done(err);
if(user)
return done(null,user);
else
{
var newUser = new ubCust;
newUser.google.id = profile.id;
newUser.google.token = token;
newUser.google.name = profile.displayName;
newUser.google.email = profile.emails[0].value;
newUser.save(function(err){
if (err)
throw err;
return done(null,newUser);
});
console.log(profile);
}
//done(null, profile, tokens);
}); //findOne
});//nextTick
}
));
};
route(authController.js)
module.exports = function(app,passport){
app.get('/api/getprofauth',isLoggedIn,function(req,res){
console.log('In getprofile authentication api');
//console.log('req.query :',req.query);
res.send(req.user);
});
app.get('/auth/google',
passport.authenticate('google',{scope: ['email','profile']})
);
app.get('/auth/google/callback',
passport.authenticate('google', {failureRedirect: '/'}),
function(req, res) {
console.log('auth success!! ',req.isAuthenticated(),req.user);
res.redirect('/api/getprofauth');
}
);
function isLoggedIn(req,res,next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
{
console.log('isAuthenticated Success');
return next();
}
else{
console.log('req.user',req.user,req.isAuthenticated());
console.log('isAuthenticated Failure');
res.redirect('/');
}
// if they aren't redirect them to the home page
}//isLoggedIn
}
app.js(server)
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var config = require('./config');
var passport = require('passport');
var cookieParser = require('cookie-parser');
app.use(cookieParser());
var session = require('express-session');
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
var authController = require('./controllers/authController.js');
var port = process.env.PORT||3000;
app.use(express.static(__dirname+ '/public'));
app.set('view engine','ejs');
app.get('/',function(req,res){
//redirecting request to home page '/' to index page
res.redirect('/index.htm');
});
mongoose.connect(config.getDBConnectionString());
app.use(passport.initialize());
app.use(passport.session());
var pp = require('./config/passport');
pp(passport);
apiController(app);
apibike(app);
appoController(app);
authController(app,passport);
app.listen(port);
I'm encountering a little problem when using passport.js with express 4.11.1
Below is my app.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
if(username == '1' && password == '1') {
var user = {username: 'test',id: 123,firstName: 'test'};
return done(null, user);
} else {
return done(null, false, {message: 'Incorrect username or password'});
}
}
));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(username, done) {
var user = {
username: 'test',
id: 123,
firstName: 'test'
};
done(null, user);
});
module.exports = passport;
Then I modified my app.js, adding the middleware
var passport = require('./auth');
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
At last, I defined in the router:
var passport = require('../auth');
router.get('/login', function (req, res, next) {
res.render('login', {title: 'Login', message: ''});
});
router.post('/login',
passport.authenticate('local',
{
successRedirect: '/user2',
failureRedirect: '/login'
}));
router.get('/user2', function(req, res) {
console.log(req.session.passport);
if(req.session.passport.user === undefined) {
res.redirect('/login');
} else {
res.render('user2', {title: 'Welcome!', user: req.user});
}
});
Now the problem that I found is that I can successfully login, however when I try to print out req.session.passport, I found the passport object in session is {}. I guess maybe it's because the passport.serializeUser function doesn't really work, but when I try printing out the user object passed to the passport.serializeUser function, it has values. Can someone help me look into this issue? Thanks in advance.
Your code looks fine, except this part:
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: { secure: true } <<<<<<<<<<
}));
docs say that you should use secure cookies when you are using https, so excluding this field should fix your problem.
secure boolean marks the cookie to be used with HTTPS only.