尽管本地策略中禁用了会话,但Passport会引发错误“无法将用户序列化到会话”

时间:2019-01-17 00:30:13

标签: node.js express authentication passport.js passport-local

我正在使用护照来处理API端点的身份验证,因此不要使用会话。我正在使用本地策略进行身份验证,我的代码如下所示:

const express = require('express');
const bodyParser = require('body-parser');
const passport = require('passport')
    , LocalStrategy = require('passport-local').Strategy;

const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());

passport.use(new LocalStrategy({ session: false }, function(username, password, done){

    // hardcoded login data for demonstration
    if (username === 'dummy-user' && password === '123456seven'){
        return done(null, { username: 'dummy-user' });
    } else {
        return done(null, false, { message: 'incorrect username or password' });
    }
}));

app.post('/login', passport.authenticate('local'), function(req, res){
    res.send(req.user);
});

app.listen(3000, function () {
    console.log("App is listening on port 3000.");
});

我按照passport-localhttps://github.com/jaredhanson/passport-local

的文档中所述的策略禁用了会话

当我尝试通过http请求“登录”时,出现以下错误:

Error: Failed to serialize user into session
    at pass (/Users/johannes/Documents/StackOverflow/passportQ/node_modules/passport/lib/authenticator.js:281:19)
    at Authenticator.serializeUser (/Users/johannes/Documents/StackOverflow/passportQ/node_modules/passport/lib/authenticator.js:299:5)
    at SessionManager.logIn (/Users/johannes/Documents/StackOverflow/passportQ/node_modules/passport/lib/sessionmanager.js:14:8)
    at IncomingMessage.req.login.req.logIn (/Users/johannes/Documents/StackOverflow/passportQ/node_modules/passport/lib/http/request.js:50:33)
    at Strategy.strategy.success (/Users/johannes/Documents/StackOverflow/passportQ/node_modules/passport/lib/middleware/authenticate.js:248:13)
    at verified (/Users/johannes/Documents/StackOverflow/passportQ/node_modules/passport-local/lib/strategy.js:83:10)
    at Strategy._verify (/Users/johannes/Documents/StackOverflow/passportQ/index.js:14:16)
    at Strategy.authenticate (/Users/johannes/Documents/StackOverflow/passportQ/node_modules/passport-local/lib/strategy.js:90:12)
    at attempt (/Users/johannes/Documents/StackOverflow/passportQ/node_modules/passport/lib/middleware/authenticate.js:361:16)
    at authenticate (/Users/johannes/Documents/StackOverflow/passportQ/node_modules/passport/lib/middleware/authenticate.js:362:7)

我可以通过更改来消除此错误

app.post('/login', passport.authenticate('local'), ...

app.post('/login', passport.authenticate('local', { session: false }), ...

我的问题是:

  1. 当我将相应的选项传递给LocalStrategy实例时,为什么没有正确禁用会话?
  2. 是否可以禁用该策略的会话,这样就不必将选项传递给API代码中的每个身份验证请求? 如果可能的话,我想在不为serializeUserdeserializeUser函数实现虚拟变量的情况下实现这一目标。
  3. 是否为该策略设置了选项?

要发送http请求,我使用了以下命令:

curl -d "username=dummy-user&password=123456seven" -X POST "http://localhost:3000/login"

0 个答案:

没有答案