0

passport.authenticate from koa-passport doesn't work with local strategy. I use no sessions, no serializing. It's just simple passport example, but the server response is always 404.

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const passport = require('koa-passport');
const Router = require('koa-router');
const LocalStrategy = require('passport-local').Strategy;

const app = new Koa();

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

passport.use(new LocalStrategy({
    session: false,
    }, (email, password, done) => {
      if(email && password){
          return done(null, [email, password]);
      }
      else {
          return done(null, false);
      }
    }
));

const router = new Router();

router.post('/auth', async (ctx) => {
    passport.authenticate('local', { session: false }, (err, user) => {
        if(!user)
            return ctx.body = 'Failed!';

        return ctx.body = { msg: 'Success' };
    });
});

app.use(router.routes());

app.listen(3000, console.log('The server is started'));

2 Answers2

0

The answer is in a depth of an issues on github repo of koa-router: We should return passport.authenticate with passed context object:

router.post('/auth', async (ctx) => {
    return passport.authenticate('local', { session: false }, (err, user) => {
        if(!user)
            return ctx.body = 'Failed!';

        return ctx.body = { msg: 'Success' };
    })(ctx, next);
});
0

I had the same issue and understood that the context object must be returned back for it to parse the response.

router.post('/auth', async (ctx) => {
    return passport.authenticate('local', { session: false }, (err, user) => {
        if(!user)
            return ctx.body = 'Failed!';

        return ctx.body = { msg: 'Success' };
    })(ctx);
});