【问题标题】:How to do Authentication with Node.js and MEAN stack?如何使用 Node.js 和 MEAN 堆栈进行身份验证?
【发布时间】:2013-09-13 13:03:11
【问题描述】:

我目前正在与一个小型开发团队一起开发基于文本的游戏。游戏需要登录,我们使用 MEAN(MongoDB、Express、Angular、Node)堆栈作为应用程序代码库,但是我被困在身份验证上,作为 Rails 开发人员,我习惯于放入 gem 并使用提供帮助。

有人对 MEAN 和身份验证有任何经验吗?

【问题讨论】:

标签: node.js mean-stack


【解决方案1】:

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);
  });
});

【讨论】:

    【解决方案2】:

    或者使用具有开箱即用用户管理功能的 mean.io。

    【讨论】:

    • 是的 - 但如果有 Passport 包会很棒,这样我们就可以mean install passport
    【解决方案3】:

    你可以看看http://meanjs.org/ 他们对 passport.js 策略进行了非常可靠的集成。 尤其有用的是 Salt 和 Crypto-Technies 的实现,以确保集成安全。在 repo 中搜索 Salz。

    https://github.com/meanjs/mean/blob/master/modules/users/server/config/strategies/local.js 用于序列化和反序列化。

    【讨论】:

      【解决方案4】:

      或者,如果您更喜欢自定义实现,我最近发布了完整的 MEAN Stack User Registration and Login Example

      这是来自处理身份验证的用户服务的 sn-p:

      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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-13
        • 2017-02-18
        • 2017-03-24
        • 1970-01-01
        • 2015-04-18
        • 2017-11-19
        相关资源
        最近更新 更多