1

Front-end: React with React-router + axios

Back-end: express with express-session, passport, passport-local, passport-local-mongoose

I want to use 24 hour login sessions and use is.Authenticated() method from passport-local to verify if user is loggedIN

I found 2 very similar questions in here, both of them are not answered:

req.isAuthenticated() returns true only after passport.authenticate. Any other route will return false value

Using Passport.js and express-session, every route but the login route sends a cookie that does not include user information

my app.js:

const sessionConfig = {
    store,
    name: "session",
    secret: secret,
    resave: false,
    saveUninitialized: true,
    domain: 'localhost:3000',
    cookie: {
        httpOnly: true,
        //secure:true,                                             //enable when deployed
        expires: Date.now() + 1000 * 60 * 60 * 24,
        maxAge: 1000 * 60 * 60 * 24,
    }
}

const corsOptions = {
  origin: "http://localhost:3000",
    credentials: true,
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    "Access-Control-Allow-Credentials": "true"
};


app.use(cors(corsOptions));
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(session(sessionConfig));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(Gymbro.authenticate()));
passport.serializeUser(Gymbro.serializeUser());
passport.deserializeUser(Gymbro.deserializeUser());

here login route that seem to work correctly:

router.post("/login", passport.authenticate("local", {session: true}), catchAsync(async (req,res)=>{
    console.log(req.isAuthenticated()) //returns true
    console.log(req.user)  // returns full user object
    console.log(req.session) // returns Session with passport part ( passport:{user: 'jon'})
    res.send("you logged in")
}))

Than a user goes to other screen in React router which will trigger get request

axios.get(`http://localhost:3001/gym/all`, {withCredentials: true}).then((res) => {
        setGyms(res.data.gyms);
router.get("/all", catchAsync(async (req, res) => {
    console.log(req.isAuthenticated()) // returns false ( i will need only authenticated people to get response)
    console.log(req.session) // returns Session but without any passport bit
    const gyms = await Gym.find({});
    res.send({ gyms });
}));

store is connected properly, Can axios be stripping my get request? even i opt withCredentials?

1 Answers1

0

I found out the reason was: On the login post route i didn“t pass { withCredentials: true } (i did only on other requests) so even that passport was doing it job with authentication, the session cookie on the front-end was not updating, therefore session on every next request was without updated authentication.