passport.js 重定向后会话丢失

passport.js session lost after redirect

我正在尝试将 passport 集成到我的 node.js 应用程序中。

app.js 文件

const app = express();
app.set('view engine', 'pug');
app.use('/libs', express.static('node_modules'));

require('../config/auth.config')(app, data, passport);
app.use((req, res, next) => {
    res.locals.user = req.user;
    next();
});

app.get('/', (req, res) => {
        // those objects are populated correctly after redirect from auth middleware
        console.log(req.session)
        console.log(req.user)
        return res.render('home');
    });
app.get('/login', console.log(req.user);
        // req.user is undefined here
        if (req.user) {
            return res.redirect('/');
        }

        return res.render('login'););
app.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/login',
}));

auth.config.js

const express = require('express');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const LocalStrategy = require('passport-local');
const MongoStore = require('connect-mongo')(session);
const config = require('./config');

const configAuth = (app, {
    users
}, passport, db) => {
    app.use(cookieParser('Purple Unicorn'));
    app.use(bodyParser.urlencoded({
        extended: true,
    }));
    app.use(bodyParser.json());
    app.use(session({
        store: new MongoStore({
            url: config.connectionString
        }),
        secret: 'Purple Unicorn',
        resave: true,
        saveUninitialized: true,
    }));
    app.use(passport.initialize());
    app.use(passport.session());

    passport.use(new LocalStrategy((username, password, done) => {
        return users.login(username, password)
            .then((user) => {
                if (user) {
                    return done(null, user);
                }
                return done(null, false);
            });
    }));

    passport.serializeUser((user, done) => {
        done(null, user._id);
    });

    passport.deserializeUser((id, done) => {
        users.getUserById(id)
            .then((user) => {
                console.log(user);
                if (user) {
                    done(null, user);
                }

                done(null, false);
            });
    });

    app.use((req, res, next) => {
        res.locals = {
            user: req.user,
        };
        next();
    });
};

module.exports = configAuth;

数据对象工作正常。

/login 上的 post 请求使用正确的数据后,我被重定向到 /,其中 console.log(req.user) 打印出正确的用户。它也被添加到 req.session 对象中。

在我跟随 link 到 /login 之后,它应该在检查 req.user 但 returns undefined 后重定向我。 mongo 中的会话已正确存储。

passport 似乎没有正确保存会话。

问题出在您的 deserializeUser 方法中,您总是 运行 done 回调两次。在 if 语句中你应该使用 return done(null, user); 来退出函数;