Currently, I am in the process of developing a web API and the workflow should go like this:
User logs in to the website --> Passport authenticates the user --> Passport stores relevant user information in a persistent session --> User can access the API as long as the session remains valid.
The issue I'm facing is that I cannot seem to get Passport to create the persistent session. The login functionality works correctly (only authorized users are able to proceed), but for some reason, Passport fails to retain any session data in the client's browser. Consequently, the user loses access to the API moving forward.
The sections of code pertinent to this problem are outlined below:
Server.js:
// Import necessary packages
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
// Setup database connection
var configDB = require('./config/database.js');
var mongoose = require('mongoose');
mongoose.connect(configDB.url);
// Include schema for training
var Training = require('./models/training');
// Configure app
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Required for passport
require('./config/passport')(passport);
app.use(require('express-session')({
cookie : {
maxAge: 3600000,
secure: false
},
secret: 'khugugjh',
resave: false,
saveUninitialized: true
});
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
...
routes.js:
...
// Define the login route
router.route('/login').post(
passport.authenticate('local-login'),
function(req, res) {
// If this function gets called, authentication was successful.
// `req.user` contains the authenticated user.
console.log('Logged in user: ' + req.user);
});
...
passport.js:
...
// Serialization and deserialization functions for Passport
passport.serializeUser(function(user, done) {
console.log('Serializing user: ' + user);
return done(null, user._id);
});
// Used to deserialize the user
passport.deserializeUser(function(id, done) {
console.log('Attempting to deserialize user.');
User.findById(id, function(err, user) {
console.log('Deserializing user: ' + user);
return done(err, user);
});
});
...