linnovate 的 MEAN 堆栈使用Passport.js 进行身份验证。 Passport 使用不同的身份验证策略。其中一种策略是用户名和密码对,他们称之为LocalStrategy。
这是来自 Passportjs-Local Github Examples Page 的示例之一
第 1 步:需要护照
在执行 npm install passport 后首先需要模块
var passport = require('passport');
第 2 步:配置“验证”功能
在 Passport 中使用 LocalStrategy。护照中的策略需要verify 函数,该函数接受凭据(在本例中为用户名和密码),并使用用户对象调用回调。在现实世界中,这将查询数据库;然而,在这个例子中,我们使用的是一组内置的用户。
passport.use(new LocalStrategy(
function(username, password, done) {
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
findByUsername(username, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Unknown user ' + username });
}
if (user.password != password) {
return done(null, false, { message: 'Invalid password' });
}
return done(null, user);
})
});
}
));
第 3 步:在应用上初始化 Passport
您需要告诉 Express 您将使用护照,并且它将为您管理会话。这是通过在应用配置期间使用 app.use() 来完成的。
app.use(passport.initialize());
app.use(passport.session());
第 4 步:在登录 URI 上配置中间件
接下来,我们需要创建一个方法,当用户尝试使用 POST 到特定 URI 登录应用程序时,该方法将接受该方法。它看起来像这样。
// POST /login
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function function will be called,
// which, in this example, will redirect the user to the home page.
//
// curl -v -d "username=bob&password=secret" http://127.0.0.1:3000/login
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }),
function(req, res) {
res.redirect('/');
});
第 5 步:设置会话
您可能必须为存储在会话中的用户对象创建自己的序列化。这是通过以下方式完成的
// Passport session setup.
// To support persistent login sessions, Passport needs to be able to
// serialize users into and deserialize users out of the session. Typically,
// this will be as simple as storing the user ID when serializing, and finding
// the user by ID when deserializing.
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
findById(id, function (err, user) {
done(err, user);
});
});