简体   繁体   English

如何使用Node.js和MEAN堆栈进行身份验证?

[英]How to do Authentication with Node.js and MEAN stack?

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和身份验证的经验?

the MEAN stack by linnovate uses Passport.js for its authentication. linnovate的MEAN堆栈使用Passport.js进行身份验证。 Passport uses different strategies for authentication. Passport使用不同的身份验证策略。 One of these strategies is a username and password pair, which they call LocalStrategy . 其中一个策略是用户名和密码对,他们称之为LocalStrategy

Here is one of the samples from the Passportjs-Local Github Examples Page 以下是Passportjs-Local Github 示例页面中的一个示例

Step 1: Require Passport 第1步:要求Passport

First you require the module after doing npm install passport 首先你做了npm安装护照后需要模块

var passport = require('passport');

Step 2: Configure 'Verify' Function 第2步:配置“验证”功能

Use the LocalStrategy within Passport. 使用Passport中的LocalStrategy。 Strategies in passport require a verify function, which accept credentials (in this case, a username and password), and invoke a callback with a user object. 护照中的策略需要verify功能,该函数接受凭证(在本例中为用户名和密码),并使用用户对象调用回调。 In the real world, this would query a database; 在现实世界中,这将查询数据库; however, in this example we are using a baked-in set of users. 但是,在这个例子中,我们使用了一组用户。

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步:在app上初始化Passport

You need to tell Express that you will be using passport and that it will be managing sessions for you. 您需要告诉Express您将使用护照并且它将为您管理会话。 This is done by using the app.use() during app configuration. 这是通过在应用程序配置期间使用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. 接下来,我们需要创建一个方法,当用户尝试通过POST到特定URI来登录应用程序时,该方法将接受。 It will look like this. 它看起来像这样。

// 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 Sessions You may have to create your own serialization for User objects that are being stored in the sessions. 步骤5:设置会话您可能必须为存储在会话中的用户对象创建自己的序列化。 That is done with the following 这是通过以下方式完成的

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

You can have a look at http://meanjs.org/ They have a very solid integration of passport.js strategies. 你可以看看http://meanjs.org/他们有一个非常可靠的passport.js策略集成。 Especally useful is the implementation of Salt and Crypto-Technies to make the integration safe. 特别有用的是Salt和Crypto-Technies的实现,以使集成安全。 Search for Salz within the repo. 在回购中搜索萨尔茨。

See https://github.com/meanjs/mean/blob/master/modules/users/server/config/strategies/local.js For serialization and deserialization. 请参阅https://github.com/meanjs/mean/blob/master/modules/users/server/config/strategies/local.js用于序列化和反序列化。

Or if you'd prefer a custom implementation, I recently posted a complete MEAN Stack User Registration and Login Example 或者,如果您更喜欢自定义实现,我最近发布了一个完整的MEAN堆栈用户注册和登录示例

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM