6
votes

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 !!

1
Does it work when you remove the cors()? I'm having the same situation and same issue :(UtkarshPramodGupta
@UtkarshPramodGupta it wouldn't work if you removed cors because you would also disable Cross Origin requests. So the front-end wouldn't be able to make any requests. Although, I'm having the same exact issue and searched the whole internet. Still can't find a way. I'm searching other ways of Authentication since passportjs doesn't seem to work with cors or I'm just doing something wrong.Eksapsy

1 Answers

2
votes

I had the same issue. In my case, I was having an SPA on the frontend with a RESFful (well, not really as we are maintaining state here) backend on Node.js. Later I found out that I was not sending the browser cookies along with the data when I used to make requests to my RESTful API. This was exactly where the issue was that what was not letting users get Deserialized because we need cookies data on the backend to find out which user has sent a particular request. Try doing the same, I hope that would solve your problem as it did mine. :)