简体   繁体   中英

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.

has anybody has any experience with MEAN and Authentication?

the MEAN stack by linnovate uses Passport.js for its authentication. Passport uses different strategies for authentication. One of these strategies is a username and password pair, which they call LocalStrategy .

Here is one of the samples from the Passportjs-Local Github Examples Page

Step 1: Require Passport

First you require the module after doing npm install passport

var passport = require('passport');

Step 2: Configure 'Verify' Function

Use the LocalStrategy within Passport. 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. 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

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.

app.use(passport.initialize());
app.use(passport.session());

Step 4: Configure Middleware on the login 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 /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. 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. Especally useful is the implementation of Salt and Crypto-Technies to make the integration safe. 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.

Or if you'd prefer a custom implementation, I recently posted a complete MEAN Stack User Registration and Login Example

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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