I search a lot on internet but I can not find the answer.
I am using my frontend on one port and my backend in another. I use cors to enable the requests and this works. But when I implement passport js and sessions with mongodb whit does not work, it means when I try to get the user with req.user this is undefined. Here is my index.js code
app.use(cors());
app.use(session({
resave: false,
saveUninitialized: false,
secret: 's3cr3et',
store: new MongoStore({
url: process.env.MONGO_URI
})
}));
app.use(passport.initialize());
app.use(passport.session());
my passport js is
Here i define my auth, serialize and deserialize user. My Auth and serialize is working well but deserialize not
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
User.findById(id, (err, user) => {
done(null, user);
});
});
passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
User.findOne({ email: email.toLowerCase() }, (err, user) => {
if (err) { return done(err); }
if (!user) { return done(null, false, { error: 'Invalid credentials.' }); }
user.comparePassword(password, (err, isMatch) => {
if (err) { return done(err); }
if (isMatch) {
return done(null, user);
}
return done(null, false, { error: 'Invalid credentials.' });
});
});
}));
I tried also cookie session instead mongo db but I guess is not the solution. The problem is the cors, for some reason passport dont read the session.
Also I tried to enable in coors credentials and specify the origin but deserialize still not set the user
app.use(cors({
credentials: true,
origin: ['http://localhost:8080']
}));
I hope you can help me because I can not get it work Thanks !!