Piper McCorkle
Piper McCorkle

Reputation: 1074

Error: Unknown authentication strategy "[object Object]"

POST localhost/api/login with the (correct) data username=test password=test gives the following:

Error: Unknown authentication strategy "[object Object]"
   at attempt (/var/www/node_modules/passport/lib/middleware/authenticate.js:166:37)
   at authenticate (/var/www/node_modules/passport/lib/middleware/authenticate.js:342:7)
   at Layer.handle [as handle_request] (/var/www/node_modules/express/lib/router/layer.js:82:5)
   at next (/var/www/node_modules/express/lib/router/route.js:110:13)
   at Route.dispatch (/var/www/node_modules/express/lib/router/route.js:91:3)
   at Layer.handle [as handle_request] (/var/www/node_modules/express/lib/router/layer.js:82:5)
   at /var/www/node_modules/express/lib/router/index.js:267:22
   at Function.proto.process_params (/var/www/node_modules/express/lib/router/index.js:321:12)
   at next (/var/www/node_modules/express/lib/router/index.js:261:10)
   at SessionStrategy.strategy.pass (/var/www/node_modules/passport/lib/middleware/authenticate.js:318:9)

Route:

app.post('/api/login', passport.authenticate(new LocalStrategy(function(username, password, done) {
  db.User.findOne({username: username}, function(err, user) {
    if (err) return done(err);
    if (!user) return done(null, false, { message: 'Username or password incorrect' });
    bcrypt.compare(password, user.passHash, function(err, res) {
      if (err) return done(err);
      if (!res) return done(null, false, { message: 'Username or password incorrect' });
      return done(null, user);
    })
  })
})))

I have bodyParser running, and I know it's working from my signup route working. What's going on here? I've been using the http://passportjs.org/guide guide and it's gotten the basics down, but why is this happening?

Upvotes: 1

Views: 3643

Answers (1)

mscdex
mscdex

Reputation: 106698

authenticate() does not accept an object, it takes in a string containing the name of a strategy that you previously configured. Your new LocalStrategy() is what gets passed to passport.use().

So you do this in your middleware definitions:

passport.use(new LocalStrategy(function(username, password, done) {
  db.User.findOne({username: username}, function(err, user) {
    if (err)
      return done(err);
    if (!user)
      return done(null, false, { message: 'Username or password incorrect' });
    bcrypt.compare(password, user.passHash, function(err, res) {
      if (err)
        return done(err);
      if (!res)
        return done(null, false, { message: 'Username or password incorrect' });
      return done(null, user);
    })
  })
}));

and you do something like this for your route:

app.post('/api/login',
  passport.authenticate('local'),
  function(req, res) {
    // authentication successful
  });

Upvotes: 4

Related Questions