如何使用 Node.js 和 MEAN 堆栈进行身份验证?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18708428/
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
How to do Authentication with Node.js and MEAN stack?
提问by jpotts18
I am currently working on a text based game with a small team of developers. The game requires login and we are using the MEAN (MongoDB, Express, Angular, Node) Stack for the application codebase, however i am stuck on authentication, as a rails developer i am used to being able to drop in a gem and use the helpers available.
我目前正在与一小群开发人员一起开发基于文本的游戏。游戏需要登录,我们正在使用 MEAN(MongoDB、Express、Angular、Node)堆栈作为应用程序代码库,但是我坚持进行身份验证,作为 Rails 开发人员,我习惯于能够放入 gem 并使用可用的助手。
has anybody has any experience with MEAN and Authentication?
有没有人对 MEAN 和身份验证有任何经验?
回答by jpotts18
the MEAN stack by linnovate uses Passport.jsfor its authentication. Passport uses different strategies for authentication. One of these strategies is a username and password pair, which they call LocalStrategy.
linnovate 的 MEAN 堆栈使用Passport.js进行身份验证。Passport 使用不同的身份验证策略。这些策略之一是用户名和密码对,他们称之为LocalStrategy。
Here is one of the samples from the Passportjs-Local Github Examples Page
这是 Passportjs-Local Github示例页面中的示例之一
Step 1: Require Passport
第 1 步:需要护照
First you require the module after doing npm install passport
首先,您在执行 npm install 护照后需要该模块
var passport = require('passport');
Step 2: Configure 'Verify' Function
第 2 步:配置“验证”功能
Use the LocalStrategy within Passport. Strategies in passport require a verifyfunction, which accept credentials (in this case, a username and password), and invoke a callback with a user object. In the real world, this would query a database; however, in this example we are using a baked-in set of users.
在 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);
})
});
}
));
Step 3: Initialize Passport on app
第 3 步:在应用程序上初始化 Passport
You need to tell Express that you will be using passport and that it will be managing sessions for you. This is done by using the app.use() during app configuration.
您需要告诉 Express 您将使用通行证,并且它将为您管理会话。这是通过在应用程序配置期间使用 app.use() 来完成的。
app.use(passport.initialize());
app.use(passport.session());
Step 4: Configure Middleware on the login URI
第 4 步:在登录 URI 上配置中间件
Next we need to create a method that will accept when a user tries to login to the app using by POST-ing to a specific URI. It will look like this.
接下来,我们需要创建一个方法,当用户尝试使用 POST-ing 到特定 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('/');
});
Step 5: Set up SessionsYou may have to create your own serialization for User objects that are being stored in the sessions. That is done with the following
第 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);
});
});
回答by Rentrop
You can have a look at http://meanjs.org/They have a very solid integration of passport.js strategies. Especally useful is the implementation of Salt and Crypto-Technies to make the integration safe. Search for Salz within the repo.
你可以看看http://meanjs.org/他们有一个非常可靠的passport.js 策略集成。特别有用的是 Salt 和 Crypto-Technies 的实现,以确保集成安全。在 repo 中搜索 Salz。
See https://github.com/meanjs/mean/blob/master/modules/users/server/config/strategies/local.jsFor serialization and deserialization.
有关序列化和反序列化,请参见 https://github.com/meanjs/mean/blob/master/modules/users/server/config/strategies/local.js。
回答by Jason
Or if you'd prefer a custom implementation, I recently posted a complete MEAN Stack User Registration and Login Example
或者,如果您更喜欢自定义实现,我最近发布了一个完整的MEAN Stack 用户注册和登录示例
Here's the snippet from the user service that handles authentication:
以下是处理身份验证的用户服务的片段:
function authenticate(username, password) {
var deferred = Q.defer();
usersDb.findOne({ username: username }, function (err, user) {
if (err) deferred.reject(err);
if (user && bcrypt.compareSync(password, user.hash)) {
// authentication successful
deferred.resolve(jwt.sign({ sub: user._id }, config.secret));
} else {
// authentication failed
deferred.resolve();
}
});
return deferred.promise;
}
回答by Lior Kesos
Or use mean.io which has user management out of the box.
或者使用 mean.io,它具有开箱即用的用户管理功能。

