Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PassportJS, how does one pass additional form fields to the local authentication strategy?

I'm using passportJS and I'm wanting to supply more than just req.body.username and req.body.password to my authentication strategy (passport-local).

I have 3 form fields: username, password, & foo

How do I go about accessing req.body.foo from my local strategy which looks like:

passport.use(new LocalStrategy(
  {usernameField: 'email'},
    function(email, password, done) {
      User.findOne({ email: email }, function(err, user) {
        if (err) { return done(err); }
        if (!user) {
          return done(null, false, { message: 'Unknown user' });
        }
        if (password != 1212) {
          return done(null, false, { message: 'Invalid password' });
        }
        console.log('I just wanna see foo! ' + req.body.foo); // this fails!
        return done(null, user, aToken);

      });
    }
));

I'm calling this inside my route (not as route middleware) like so:

  app.post('/api/auth', function(req, res, next) {
    passport.authenticate('local', {session:false}, function(err, user, token_record) {
      if (err) { return next(err) }
      res.json({access_token:token_record.access_token});
   })(req, res, next);

  });
like image 978
k00k Avatar asked Aug 02 '12 19:08

k00k


People also ask

What are Passportjs strategies?

Strategies are responsible for authenticating requests, which they accomplish by implementing an authentication mechanism. Authentication mechanisms define how to encode a credential, such as a password or an assertion from an identity provider (IdP), in a request.

How does Passport JS handle authorization?

Authorization is performed by calling passport. authorize() . If authorization is granted, the result provided by the strategy's verify callback will be assigned to req.account . The existing login session and req.

What is Passport local strategy?

passport-local is the strategy you would use if you are authenticating against a username and password stored 'locally' i.e. in the database of your app - 'local' means local to your application server, not local to the end user. passport-jwt is the strategy for using JSON Web Tokens.

What does Passport authenticate () do?

In this route, passport. authenticate() is middleware which will authenticate the request. By default, when authentication succeeds, the req. user property is set to the authenticated user, a login session is established, and the next function in the stack is called.


2 Answers

There's a passReqToCallback option that you can enable, like so:

passport.use(new LocalStrategy(
  {usernameField: 'email', passReqToCallback: true},
  function(req, email, password, done) {
    // now you can check req.body.foo
  }
));

When, set req becomes the first argument to the verify callback, and you can inspect it as you wish.

like image 167
Jared Hanson Avatar answered Oct 21 '22 23:10

Jared Hanson


In most common cases we need to provide 2 options for login

  • with email
  • with mobile

Its simple , we can take common filed username and query $or by two options , i posted following snippets,if some one have have same question .

We can also use 'passReqToCallback' is best option too , thanks @Jared Hanson

passport.use(new LocalStrategy({
    usernameField: 'username', passReqToCallback: true
}, async (req, username, password, done) => {
    try {
        //find user with email or mobile
        const user = await Users.findOne({ $or: [{ email: username }, { mobile: username }] });

        //if not handle it
        if (!user) {
            return done(null, {
                status: false,
                message: "That e-mail address or mobile doesn't have an associated user account. Are you sure you've registered?"
            });
        }

        //match password
        const isMatch = await user.isValidPassword(password);
        debugger
        if (!isMatch) {
            return done(null, {
                status: false,
                message: "Invalid username and password."
            })
        }

        //otherwise return user
        done(null, {
            status: true,
            data: user
        });
    } catch (error) {
        done(error, {
            status: false,
            message: error
        });
    }
}));
like image 43
Bhagvat Lande Avatar answered Oct 21 '22 23:10

Bhagvat Lande