乐闻世界logo
搜索文章和话题

How to delete cookie on logout in express + passport js?

1个答案

1

When implementing user logout in the Express framework combined with Passport.js for user authentication, it typically involves invalidating the session and deleting authentication-related cookies. Specifically, to delete cookies during logout, we can follow these steps:

  1. Set Cookie: First, ensure that cookies are set during login. This is typically done in the Passport login callback, for example, using the res.cookie() method.

  2. Create Logout Route: In Express, you need a dedicated route to handle user logout.

  3. Clear Cookies: In this logout route, in addition to calling req.logout() to clear the session, you also need to clear the cookies.

The following is a simple code example demonstrating this process:

javascript
const express = require('express'); const passport = require('passport'); const app = express(); // Assume Passport initialization and session configuration are already set // Login route app.post('/login', passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }), (req, res) => { // Set cookie, e.g., sessionID res.cookie('session_id', '123456'); }); // Logout route app.get('/logout', (req, res) => { // Logout user req.logout(); // Clear all related cookies res.clearCookie('session_id'); // Redirect to login page or homepage res.redirect('/login'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });

In this example, after login, a cookie named session_id is set. Then, in the logout route, we first call req.logout() to clear the session (a Passport.js method), followed by using res.clearCookie('session_id') to delete the specified cookie. Finally, the user is redirected to the login page.

This approach ensures that when users log out, their session information and authentication-related cookies are cleared, thereby enhancing the application's security.

2024年8月12日 14:30 回复

你的答案