Why is PassportJS in Node not removing session on

2020-01-26 03:35发布

I am having trouble getting my system to log out with PassportJS. It seems the logout route is being called, but its not removing the session. I want it to return 401, if the user is not logged in in specific route. I call authenticateUser to check if user is logged in.

Thanks a lot!

/******* This in index.js *********/
// setup passport for username & passport authentication
adminToolsSetup.setup(passport);

// admin tool login/logout logic
app.post("/adminTool/login",
    passport.authenticate('local', {
        successRedirect: '/adminTool/index.html',
        failureRedirect: '/',
        failureFlash: false })
);
app.get('/adminTool/logout', adminToolsSetup.authenticateUser, function(req, res){
    console.log("logging out");
    console.log(res.user);
    req.logout();
    res.redirect('/');
});


// ******* This is in adminToolSetup ********
// Setting up user authentication to be using user name and passport as authentication method,
// this function will fetch the user information from the user name, and compare the password     for authentication
exports.setup = function(passport) {
    setupLocalStrategy(passport);
    setupSerialization(passport);
}

function setupLocalStrategy(passport) {
    passport.use(new LocalStrategy(
        function(username, password, done) {
            console.log('validating user login');
            dao.retrieveAdminbyName(username, function(err, user) {
                if (err) { return done(err); }
                if (!user) {
                    return done(null, false, { message: 'Incorrect username.' });
                }
                // has password then compare password
                var hashedPassword = crypto.createHash('md5').update(password).digest("hex");
                if (user.adminPassword != hashedPassword) {
                    console.log('incorrect password');
                    return done(null, false, { message: 'Incorrect password.' });
                }
                console.log('user validated');
                return done(null, user);
            });
        }
    ));
}

function setupSerialization(passport) {
    // serialization
    passport.serializeUser(function(user, done) {
        console.log("serialize user");
        done(null, user.adminId);
    });

    // de-serialization
    passport.deserializeUser(function(id, done) {
        dao.retrieveUserById(id, function(err, user) {
            console.log("de-serialize user");
            done(err, user);
        });
    });
}

// authenticating the user as needed
exports.authenticateUser = function(req, res, next) {
    console.log(req.user);
    if (!req.user) {
        return res.send("401 unauthorized", 401);
    }
    next();
}

20条回答
男人必须洒脱
2楼-- · 2020-01-26 04:20

None of the answers worked for me so I will share mine

app.use(session({
    secret: 'some_secret',
    resave: false,
    saveUninitialized: false,
   cookie: {maxAge: 1000} // this is the key
}))

and

router.get('/logout', (req, res, next) => {
    req.logOut()
    req.redirect('/')
})
查看更多
不美不萌又怎样
3楼-- · 2020-01-26 04:22

I was having the same issues, capital O fixed it;

app.get('/logout', function (req, res){
  req.logOut()  // <-- not req.logout();
  res.redirect('/')
});

Edit: this is no longer an issue.

查看更多
何必那么认真
4楼-- · 2020-01-26 04:23

Brice’s answer is great, but I still noticed an important distinction to make; the Passport guide suggests using .logout() (also aliased as .logOut()) as such:

app.get('/logout', function(req, res){
  req.logout();
  res.redirect('/'); //Can fire before session is destroyed?
});

But as mentioned above, this is unreliable. I found it behaved as expected when implementing Brice’s suggestion like this:

app.get('/logout', function (req, res){
  req.session.destroy(function (err) {
    res.redirect('/'); //Inside a callback… bulletproof!
  });
});

Hope this helps!

查看更多
该账号已被封号
5楼-- · 2020-01-26 04:24

I was having the same issue, and it turned out to not be a problem with Passport functions at all, but rather in the way I was calling my /logout route. I used fetch to call the route:

(Bad)

fetch('/auth/logout')
  .then([other stuff]);

Turns out doing that doesn't send cookies so the session isn't continued and I guess the res.logout() gets applied to a different session? At any rate, doing the following fixes it right up:

(Good)

fetch('/auth/logout', { credentials: 'same-origin' })
  .then([other stuff]);
查看更多
6楼-- · 2020-01-26 04:24

I faced the similar problem with Passport 0.3.2.

When I use Custom Callback for the passport login and signup the problem persisted.

The problem was solved by upgrading to Passport 0.4.0 and adding the lines

app.get('/logout', function(req, res) {
    req.logOut();
    res.redirect('/');
});
查看更多
神经病院院长
7楼-- · 2020-01-26 04:25

I'm working with a programmer, that suggests to remove user of req:

app.get('/logout', function (req, res){
  req.session.destroy(function (err) {
    req.user = null;
    res.redirect('/'); //Inside a callback… bulletproof!
  });
});

Reason: we need to remove from req(passportjs also doing this but async way) because there is no use of user data after logout even this will save memory and also might be passportjs found user data and may create new session and redirect(but not yet happen) By the ways, this is our responsibility to remove irrelevant thing. PassportJS assign data into req.user after login and also remove if we use req.logout() but it may not works properly some times as NodeJS Asynchronous in nature

查看更多
登录 后发表回答