0

here's my registration route:

(I use passport-local-mongoose)

router.post("/register", (req,res)=>{
    console.log(req.body);
    User.register({
            username: req.body.username,
            mail: req.body.email
        }, req.body.password, (err, user)=>{
            err ? console.log(err) : passport.authenticate("local")(req, res, () => {
                console.log(user.username + " registered and logged in.");
                // console.log(user);
                res.send(req.isAuthenticated());
                console.log(req.user);

              })

        })
    
});

After user get created and authenticated, everything is fine. I have req.user object, I have isAuthenticated as true (I tried to log it with interval of 1 sec - always returns true). But, if I try to check if user is authenticated, from some different route, for example:

router.get("/getUser", (req, res)=>{
  res.send(req.user);
  console.log(req.isAuthenticated());
})

I immediately get false in the console and undefined from req.user. Any ideas? Looks like the problem is - any request to the server after authentication just removes req.user

meAndrew
  • 144
  • 1
  • 13

2 Answers2

0

Late answer, but i just run into the same problem yesterday, and needed to learn hard way as here was no answer :).

Your cookie on the front-end is not getting updated if you don´t specify it when sending request by adding: { withCredentials: true }, and you MUST do it on register / login POST routes

f.e:

await axios.post("http://localhost:3001/register", payload, { withCredentials: true } )

but for that to go through you have to pass some cors options on your server:

const corsOptions = {
    origin: "http://localhost:3000", // notice origin won´t work as any (*) from that point
    credentials: true,
    "Access-Control-Allow-Credentials": true
};


app.use(cors(corsOptions));
'''

  • I don't remember if I used { withCredentials: true } and Cors options, but 99.9% I did. In the end I just switched to JWT authentication) – meAndrew Sep 12 '22 at 03:36
0

While setting up session, set saveUnintialized as false, Choosing false is useful for implementing login sessions. The default value is true, but using the default has been deprecated, as the default will change in the future.

app.use(session({
    secret: [YOUR_SECRET],
    resave: false,
    saveUninitialized: false
}));