Home > Enterprise >  Passport JS does not allow to logout (ExpressJS, PassportJS, React)
Passport JS does not allow to logout (ExpressJS, PassportJS, React)

Time:12-20

I'm implementing SSO authentication through passport google oidc strategy. Everything works fine for authentication, but I encounter some problems while logging out.

So, here's my Backend logout route

authRouter.post('/logout', async (req, res, next) => {
    req.logout(req.user, (err)=> {
        if (err) return next(err);
    })
    req.session.destroy((err) => {
        res.clearCookie('connect.sid');
    });
})

Here's Logout Handler on FrontEnd:

const handlerLogOut = async () => {
        await axios.post('/api/auth/logout', {withCredentials: true})
            .then(res => {
                console.log('response ', res);
            })
    }

But while destroying the session, I encounter the next problem which prevent me from logging out:

<MyDisk>\<My Folder>\<Project Folder>\server\node_modules\passport\lib\sessionmanager.js:83
    req.session.regenerate(function(err) {
                ^

TypeError: Cannot read properties of undefined (reading 'regenerate')
    at Statement.<anonymous> (<MyDisk>\<My Folder>\<Project Folder>\server\node_modules\passport\lib\sessionmanager.js:83:17)
    at Statement.<anonymous> <MyDisk>\<My Folder>\<Project Folder>\server\node_modules\connect-sqlite3\lib\connect-sqlite3.js:119:32)

It seems that session manager trying to regenerate the session which does not exist anymore and here's the error

I've implemented the solution showed in the next question req.session.destroy and passport logout aren't destroying cookie on client side but that doesn't work for me.

Pure req.logout doesn't work too. Session does not destroy and req.user still has user after req.logout has been called

CodePudding user response:

I figured it out. Deleted req.destroy.session()

authRouter.post('/logout', async (req, res, next) => {
req.logout(req.user, (err)=> {
    if (err) return next(err);
})
res.clearCookie('connect.sid');
res.send({isAuth: req.isAuthenticated(), user: req.user})})

And on the front-side:

await axios.post('/api/auth/logout',{}, {withCredentials: true})
        .then(res => {
            console.log('response ', res);
            setUser(res.data.user)
        })
        .catch(e=> console.log(e))

Instead of:

await axios.post('/api/auth/logout',{withCredentials: true})
        .then(res => {
            console.log('response ', res);
            setUser(res.data.user)
        })
        .catch(e=> console.log(e))
  • Related