0
我試圖讓Passport在本地策略上使用自定義回調。 我在前端和nodejs中使用AngularJS,在後端表示。
到目前爲止,我已經能夠完成整個工作流程。我的問題是,顯然這個策略在使用自定義回調函數時不會調用驗證回調中的反序列化/序列化函數。好奇的是,當我讓護照處理剩下的部分而沒有給出自定義回調函數被調用時,我在控制檯中打印了'foo'或'bar'。
或者我可能錯過了一些重要的東西,但我找不到任何文檔或其他來源可以解決我的問題。NodeJS Passport本地策略自定義回調不會觸發序列化/反序列化功能
var sessionOpts = {
saveUninitialized: true, // saved new sessions
resave: false, // do not automatically write to the session store
store: sessionStore,
secret: sessionSecret,
cookie : { httpOnly: true, maxAge: config.session.maxAge } // configure when sessions expires
};
var server = express();
// log all requests to the console
server.use(morgan('dev'));
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({
extended: true
}));
server.use(session(sessionOpts));
server.use(passport.initialize());
server.use(passport.session());
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
console.log('foo')
var sessionUser = {
id: user._id,
email: user.email
};
done(null, sessionUser)
});
// used to deserialize the user
passport.deserializeUser(function(sessionUser, done) {
console.log('bar')
done(null, sessionUser);
});
passport.use('local-signin', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function (req, email, password, done) { // callback with email and password from our form
// attempt to authenticate user
User.getAuthenticated(email, password, function (err, user, reason) {
if (err) return done(err);
// login was successful if we have a user
if (user) {
// handle login success
return done(null, user);
}
// otherwise send back the reason why it failed
return done(null, false, reason)
});
}));
而且這是在明確定義(錯誤處理只是虛設錯誤代碼現在)我的路線:
server.get('/signin', function(req, res, next) {
passport.authenticate('local-signin', function(err, user, reason) {
if (err) {
return res.sendStatus(500);
}
// login was successful if we have a user
if (user) {
// handle login success
return res.send(user);
}
// otherwise we can determine why we failed
var reasons = User.failedLogin;
switch (reason) {
case reasons.NOT_FOUND:
return res.sendStatus(401);
break;
case reasons.PASSWORD_INCORRECT:
// note: these cases are usually treated the same - don't tell
// the user *why* the login failed, only that it did
return res.sendStatus(402);
break;
case reasons.MAX_ATTEMPTS:
// send email or otherwise notify user that account is
// temporarily locked
return res.sendStatus(403);
break;
default:
return res.sendStatus(500)
}
})(req, res, next);
});
預先感謝您!