node.js 未使用passport.jspassport.initialize()中间件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16781294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:37:24  来源:igfitidea点击:

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

node.jsexpressmongooserestful-authenticationpassport.js

提问by Naor

I am using node with express + mongoose and trying to use passport.js with restful api.
I keep getting this exception after authentication success (I see the callback url on the browser):

我正在使用带有 express + mongoose 的节点,并尝试使用带有restful api 的passport.js。
身份验证成功后,我不断收到此异常(我在浏览器上看到回调 url):

/Users/naorye/dev/naorye/myproj/node_modules/mongoose/lib/utils.js:419
        throw err;
              ^
Error: passport.initialize() middleware not in use
    at IncomingMessage.req.login.req.logIn (/Users/naorye/dev/naorye/myproj/node_modules/passport/lib/passport/http/request.js:30:30)
    at Context.module.exports.delegate.success (/Users/naorye/dev/naorye/myproj/node_modules/passport/lib/passport/middleware/authenticate.js:194:13)
    at Context.actions.success (/Users/naorye/dev/naorye/myproj/node_modules/passport/lib/passport/context/http/actions.js:21:25)
    at verified (/Users/naorye/dev/naorye/myproj/node_modules/passport-facebook/node_modules/passport-oauth/lib/passport-oauth/strategies/oauth2.js:133:18)
    at Promise.module.exports.passport.use.GitHubStrategy.clientID (/Users/naorye/dev/naorye/myproj/config/passport.js:91:24)
    at Promise.onResolve (/Users/naorye/dev/naorye/myproj/node_modules/mongoose/node_modules/mpromise/lib/promise.js:162:8)
    at Promise.EventEmitter.emit (events.js:96:17)
    at Promise.emit (/Users/naorye/dev/naorye/myproj/node_modules/mongoose/node_modules/mpromise/lib/promise.js:79:38)
    at Promise.fulfill (/Users/naorye/dev/naorye/myproj/node_modules/mongoose/node_modules/mpromise/lib/promise.js:92:20)
    at /Users/naorye/dev/naorye/myproj/node_modules/mongoose/lib/query.js:1822:13

I have read that I should put app.use(passport.initialize());and app.use(passport.session());before app.use(app.router);and this is what I did. Here is my express.js that registers the middlewares:

我已经读过我应该把app.use(passport.initialize());和放在app.use(passport.session());之前app.use(app.router);,这就是我所做的。这是我注册中间件的 express.js:

var express = require('express'),
    mongoStore = require('connect-mongo')(express),
    flash = require('connect-flash'),
    helpers = require('view-helpers');

module.exports = function (app, config, passport) {
    app.set('showStackError', true);
    // should be placed before express.static
    app.use(express.compress({
        filter: function (req, res) {
            return /json|text|javascript|css/.test(res.getHeader('Content-Type'));
        },
        level: 9
    }));
    app.use(express.favicon());
    app.use(express.static(config.root + '/public'));

    app.use(express.logger('dev'));

    // set views path, template engine and default layout
    app.set('views', config.root + '/app/views');
    app.set('view engine', 'jade');

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

        // dynamic helpers
        app.use(helpers(config.app.name));

        // cookieParser should be above session
        app.use(express.cookieParser());

        // bodyParser should be above methodOverride
        app.use(express.bodyParser());
        app.use(express.methodOverride());

        // express/mongo session storage
        app.use(express.session({
            secret: 'linkit',
            store: new mongoStore({
                url: config.db,
                collection : 'sessions'
            })
        }));

        // connect flash for flash messages
        app.use(flash());

        // routes should be at the last
        app.use(app.router);

        // assume "not found" in the error msgs
        // is a 404. this is somewhat silly, but
        // valid, you can do whatever you like, set
        // properties, use instanceof etc.
        app.use(function(err, req, res, next){
            // treat as 404
            if (~err.message.indexOf('not found')) {
                return next();
            }

            // log it
            console.error(err.stack);

            // error page
            res.status(500).render('500', { error: err.stack });
        });

        // assume 404 since no middleware responded
        app.use(function(req, res, next){
            res.status(404).render('404', {
                url: req.originalUrl,
                error: 'Not found'
            });
        });
    });
};

What is wrong?

怎么了?

UPDATEAccording to @Peter Lyons I have changed the configurations order to the following, but I still got the same error:

更新根据@Peter Lyons,我已将配置顺序更改为以下内容,但我仍然遇到相同的错误:

var express = require('express'),
    mongoStore = require('connect-mongo')(express),
    flash = require('connect-flash'),
    helpers = require('view-helpers');

module.exports = function (app, config, passport) {
    app.set('showStackError', true);
    // should be placed before express.static
    app.use(express.compress({
        filter: function (req, res) {
            return /json|text|javascript|css/.test(res.getHeader('Content-Type'));
        },
        level: 9
    }));
    app.use(express.favicon());
    app.use(express.static(config.root + '/public'));

    app.use(express.logger('dev'));

    // set views path, template engine and default layout
    app.set('views', config.root + '/app/views');
    app.set('view engine', 'jade');

    app.configure(function () {

        // dynamic helpers
        app.use(helpers(config.app.name));

        // cookieParser should be above session
        app.use(express.cookieParser());

        // bodyParser should be above methodOverride
        app.use(express.bodyParser());
        app.use(express.methodOverride());

        // express/mongo session storage
        app.use(express.session({
            secret: 'linkit',
            store: new mongoStore({
                url: config.db,
                collection : 'sessions'
            })
        }));

        // connect flash for flash messages
        app.use(flash());

        // use passport session
        app.use(passport.initialize());
        app.use(passport.session());

        // routes should be at the last
        app.use(app.router);

        // assume "not found" in the error msgs
        // is a 404. this is somewhat silly, but
        // valid, you can do whatever you like, set
        // properties, use instanceof etc.
        app.use(function(err, req, res, next){
            // treat as 404
            if (~err.message.indexOf('not found')) {
                return next();
            }

            // log it
            console.error(err.stack);

            // error page
            res.status(500).render('500', { error: err.stack });
        });

        // assume 404 since no middleware responded
        app.use(function(req, res, next){
            res.status(404).render('404', {
                url: req.originalUrl,
                error: 'Not found'
            });
        });
    });
};

回答by Peter Lyons

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.

按照这个例子来避免乱序中间件地狱,express 让它很容易进入。直接来自文档。请注意您的如何与此不完全匹配。

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
  1. cookie解析器
  2. 会议
  3. 护照.初始化
  4. 护照.session
  5. 应用程序路由器

You

  1. passport.initialize
  2. passport.session
  3. cookieParser
  4. session
  5. app.router
  1. 护照.初始化
  2. 护照.session
  3. cookie解析器
  4. 会议
  5. 应用程序路由器

回答by Matthias M

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

更新:仅适用于表达版本 3,版本 4 不再支持 app.configure()

回答by Jiayi Hu

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

在我的情况下,错误是因为我试图在req.login不绑定this到 的情况下进行承诺req,因此在调用该函数时它找不到passport设置。如果您使用的是 Node v8 req.login.bind(req)promisify则解决方案是在将其传递给之前进行绑定。

回答by Micha? Dobi Dobrzański

What has helped me also was to put routesAFTER cookiesconfig:

对我有帮助的还有在cookie配置之后放置路由

// 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);

回答by Isak La Fleur

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

Peter Lyons 的回答帮助我解决了它,但我以不同的方式解决了它。

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 repofor the whole code and not only the code snippet here.

查看我的GitHub 存储库以获取整个代码,而不仅仅是此处的代码片段。

回答by ruwan800

In my case (same error message), I was developing a custom strategy and I don't need to use a session. I just forgot to add session: falsein my route authenticatemiddleware.

在我的情况下(相同的错误消息),我正在开发一个自定义策略,我不需要使用 session。我只是忘了添加session: false我的路由authenticate中间件。

  app.post('/api/public/auth/google-token',
    passport.authenticate('google-token', {
      session: false
    }),
    function (req: any, res) {
      res.send("hello");
    }
  );