NodeJs passport local strategy authentication

Alex Zhulin Source

I want to create pretty simple authentication in my NodeJs web application using passport localStrategy.

app.post('/login', function(req, res) {
  console.log('before auth');
  passport.authenticate('local'),
    function(req, res) {
      // If this function gets called, authentication was successful.
      // `req.user` contains the authenticated user.
      // res.redirect('/users/' + req.user.username);
      console.log('auth is ok');
    }
});

What I've done:

  1. I have web form with fields login and password and action = "/login"

  2. In routers in my application I have route for login like this

After form submitted I can see in my console "before auth" which means that router is working. But I cant see "auth is ok" which means that authentication does not succeeded.

How can I implement passport.authenticate function in my application?

node.jsauthenticationpassport.js

Answers

answered 2 years ago Elmer Dantas #1

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

  passport.use(new LocalStrategy({
    usernameField: 'email',
    passwordField: 'password' 
  }, function(email, password, next) {
    //do what you want here
    //call next(pass parameter here (i.e error, object)
  }));


app.post('/login', function(req, res) {
      console.log('before auth');
      passport.authenticate('local', function(err, anotherthing){
      //err and anotherThing are the parameters send by strategy (next function). 

       });
    });

Also take a look here. For more details to accomplish this. Kind regards

comments powered by Disqus