passport.js passport.initialize() middleware not in use

喜夏-厌秋 提交于 2019-11-27 06:03:35

Follow the example to avoid the out-of-order middleware hell that express makes it so easy to enter. Straight from the docs. Note how yours does not match this exactly.

var app = express();
app.use(require('serve-static')(__dirname + '/../../public'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());

Docs

  1. cookieParser
  2. session
  3. passport.initialize
  4. passport.session
  5. app.router

You

  1. passport.initialize
  2. passport.session
  3. cookieParser
  4. session
  5. app.router

In my case (same error message) I've forgotten to add the passport initializations at all:

app.configure(function () {
    ...
    app.use(passport.initialize());
    app.use(passport.session());
});

UPDATE: Only working up to express version 3, version 4 does not support app.configure() anymore

In my case the error was because I was trying to promisify req.login without binding this to req, so when the function was called it could not find passport settings. The solution is binding req.login.bind(req) before passing it to promisify if you are using Node v8.

Peter Lyons answer helped me to solve it, but i solved it in abit different way.

app.use(
  cookieSession({
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: [keys.cookieKey],
  }),
);
app.use(passport.initialize());
app.use(passport.session());

Have a look at my GitHub repo for the whole code and not only the code snippet here.

What has helped me also was to put routes AFTER cookies config:

// init Cookies:
app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,
        keys: [keys.cookieKey]
    })
);
app.use(passport.initialize());
app.use(passport.session());

// init routes
const authRoutes = require("./routes/authRoutes")(app);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!