What am I missing about express sessions and cookies?
Right after i bountied this i discovered that it was a combination of using localhost and not setting useCredentials on the xhr request. The localhost is what tripped me up you have to use the fully qualified 127.0.0.1 and to add to the headache, the http files are served on a different port, so had to change the wildcard to reflect that.
so...
//where the server runs on 127.0.0.1:3000 but the http runs from :9000
app.use(session({
name:'some_session',
secret: 'lalala',
resave: true,
saveUninitialized: false,
cookie: { maxAge: 365 * 24 * 60 * 60 * 1000,httpOnly: false , domain:'127.0.0.1:9000'},
store: sessionStore
}));
res.header("Access-Control-Allow-Origin", "http://127.0.0.1:9000");
//important
$http request (angular): useCredentials: true
I used to have this issues.
ps: All the following code is provided by:
MEAN.JS
just started to use passport: http://passportjs.org/
"passport": "~0.2.0",
"passport-facebook": "~1.0.2",
"passport-github": "~0.1.5",
"passport-google-oauth": "~0.1.5",
"passport-linkedin": "~0.1.3",
"passport-local": "~1.0.0",
"passport-twitter": "~1.0.2",
basically I just do: express.js
// CookieParser should be above session
app.use(cookieParser());
// Express MongoDB session storage
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
app.use( function (req, res, next) {
if ( req.method === 'POST' && (req.url === '/auth/signin'||req.url === '/auth/login') ) {
if ( req.body.rememberme ) {
req.session.cookie.maxAge = 2592000000; // 30*24*60*60*1000 Rememeber 'me' for 30 days
} else {
req.session.cookie.expires = false;
}
}
next();
});
// use passport session
app.use(passport.initialize());
app.use(passport.session());
create a passport.js
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
User = require('mongoose').model('User'),
path = require('path'),
config = require('./config');
/**
* Module init function.
*/
module.exports = function() {
// Serialize sessions
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// Deserialize sessions
passport.deserializeUser(function(id, done) {
User.findOne({
_id: id
}, '-salt -password', function(err, user) {
done(err, user);
});
});
// Initialize strategies
config.getGlobbedFiles('./config/strategies/**/*.js').forEach(function(strategy) {
require(path.resolve(strategy))();
});
};
inside of strategies folder I did those files:
locals.js
`
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('mongoose').model('User');
module.exports = function() {
// Use local strategy
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(email, password, done) {
User.findOne({
email: email
}).select('-__v -notes -tags').exec(function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, {
message: 'Unknown user or invalid password'
});
}
if (!user.authenticate(password)) {
return done(null, false, {
message: 'Unknown user or invalid password'
});
}
user.password = undefined;
user.salt = undefined;
user.notes = undefined;
user.tags = [];
return done(null, user);
});
}
));
};
and finally to login I just do this:
user.auth.js
/**
* Signin after passport authentication
*/
exports.signin = function(req, res, next) {
console.log(req.body);
passport.authenticate('local', function(err, user, info) {
if (err || !user) {
res.status(400).send(info);
} else {
// Remove sensitive data before login
user.password = undefined;
user.salt = undefined;
user.notes = undefined;
user.tags = [];
user.resetPasswordToken = undefined;
req.login(user, function(err) {
if (err) {
res.status(400).send(err);
} else {
res.json(user);
}
});
}
})(req, res, next);
};