简体   繁体   中英

req.isAuthenticated() changes on redirect?

  1. User submits sign in POST data. passport.js authenticates. req.isAuthenticated() is true .
  2. Redirect user to homepage from sign in route
    • In hompage route, req.isAuthenticated() is now false .
    • Reload homepage (browser GET). Now homepage req.isAuthenticated() reads true and remains true in subsequent requests until signed out.

I would say, this happens about 80% of the time. The other 20%, hompage req.isAuthenticated() is true on redirect and subsequent reloads.

I found a similar question , but I don't think the answer doesn't seem correct as pointed put by the comment and since with my setup subsequent requests are correctly authenticated until signed out.

router.post('/sign_in', (req, res) =>
{
    passport.authenticate
    (
        'local',
        (err, user, info) =>
        {
            if(!err && user)
            {
                req.logIn(user, (err) =>
                {
                    if(!err)
                    {
                        console.log('s', req.isAuthenticated()); // <-- true
                        res.setHeader('Cache-Control', 'no-cache');
                        return res.redirect('/');
                    }
                });
            }
        }
    )(req, res);
}

And :

router.get('/', async (req, res) =>
{
   console.log('h', req.isAuthenticated()); // <-- false ???
   res.send();
}

If it matters, my session setup looks like this:

app.use
(
    session
    ({
        store             : //...
        secret            : process.env.SESSION_SECRET,
        resave            : false,
        saveUninitialized : true,
        cookie            :
        {
            httpOnly : false,
            secure   : false,
            maxAge   : null
        }
    })
);

How might this be fixed ?

The problem seems to be caused by a bug. See:

The workaround is to save session before redirecting.

req.session.save(() =>
{
    return res.redirect('/');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM