NodeJS - Logging out a user but browser back button allows me to go into previous session

32 views Asked by At
    // Disable caching for sensitive pages
    app.use((req, res, next) => {
    res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
    res.header('Expires', '-1');
    res.header('Pragma', 'no-cache');
    next();
    });


    // Passport authentication
    app.post('/login',
    passport.authenticate('local', {
    successRedirect: '/dashboard',
    failureRedirect: '/login',
    failureFlash: true  
    })
    );

    // Middleware for session handling
    app.use(session({
    secret: process.env.SESSION_SECRET || process.env.DEFAULT_SESSION_SECRET,
    resave: false,
    saveUninitialized: true,
    cookie: {
        maxAge: 60 * 60 * 1000, // 1 hour
        secure: process.env.NODE_ENV === 'production',
        httpOnly: true,
        sameSite: 'strict',
    },
    }));


    // Logout route
    app.get('/logout', (req, res) => {
    req.flash('success', 'Logged out successfully');
    req.session.destroy(err => {
            if (err) {
                console.error('Error destroying session:', err);
            }
            res.redirect('/');
        });
    });

Hi All,

I log into my application and after clicking logout I am still able to go back to my previous session, which is a security concern for me. I even manually close the browser, then reopen it and if I copy and paste the URL of my previous session I am still able to see it.

I am disabling caching, authenticating the user with Passport Local Strategy, using middleware for session handling and destroying the session after logging out successfully. I attach the relevant code I have tried many solutions by looking at suggestions online but nothing works and it is driving me crazy.

What I am doing wrong?

2

There are 2 answers

0
Sachin Jariyal On

What about that cookie? Are you destroying it also on logout? Make sure in your browser that the cookie is clearing out on logout.

0
Maven On

Fixed it thanks.

It was the order of my middleware (I have plenty) which wasn't right. Many thanks for your willing to help BTW! Yes, cookies are deleted (checked on Network tab in dev tools view).