我正在使用护照来处理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-local
:https://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 }), ...
serializeUser
和deserializeUser
函数实现虚拟变量的情况下实现这一目标。要发送http请求,我使用了以下命令:
curl -d "username=dummy-user&password=123456seven" -X POST "http://localhost:3000/login"