我正在努力让我的Passport 本地策略发挥作用.

我已经设置了这个中间件:

passport.use(new LocalStrategy(function(username, password, done) {
    //return done(null, user);
    if (username=='ben' && password=='benny'){
        console.log("Password correct");
        return done(null, true);
    }
    else
        return done(null, false, {message: "Incorrect Login"});
}));

但在这里

app.use('/admin', adminIsLoggedIn, admin);

function adminIsLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on 
    if (req.isAuthenticated())
        return next();

    // if they aren't redirect them to the home page
    res.redirect('/');
}

它总是失败并重定向到主页.

我不明白为什么会这样?为什么不能认证?

在我的控制台中,我可以看到Password Correct正在打印.

推荐答案

我也有类似的问题.passport express会话可能需要中间件.按以下顺序使用中间件修复它:(Express 4)

var session = require('express-session');

// required for passport session
app.use(session({
  secret: 'secrettexthere',
  saveUninitialized: true,
  resave: true,
  // using store session on MongoDB using express-session + connect
  store: new MongoStore({
    url: config.urlMongo,
    collection: 'sessions'
  })
}));

// Init passport authentication 
app.use(passport.initialize());
// persistent login sessions 
app.use(passport.session());

Node.js相关问答推荐

链接Inbox类方法,范围在哪里以及为什么发生变化?

Mongoose:如何在文档中推送到Caped(有限大小,滚动窗口)数组?

MongoDB-$Lookup未获得适当的结果

是否可以在MongoDB中比较和匹配引用文档中的字段

运行本地移动自动化测试时,在onPrepare钩子中,ERROR @wdio/cli:utils: A service failed in the 'onPrepare'

Postgressql的BIGSERIAL自增序列,即使由于唯一约束错误没有创建行,也会自动增加

我如何保护nodejs中的路由

为什么 client.on("messageCreate") 的 TextChannel 中缺少 nsfw 属性?

Typescript typeRoots 未检测到类型定义

如何为单个 mongo nodejs 驱动程序找到最佳连接池大小

Express.js cookie setter 的 Domain 属性:如何与 *多个 * 域共享 cookie?

Google Calendar API FreeBusy 外部用户

在数组的另一个对象中获取数组的mongoose 对象

如何在 mongoDB 中进行全动态搜索?

Base64 编码一个 javascript 对象

React Native ios build:找不到 node

为什么模块级返回语句在 Node.js 中起作用?

node.js 中存储的模块变量在什么范围内?

Bootstrap 中的 Grunt 依赖冲突

为什么 Node.js 被命名为 Node.js?