Skip to content
Advertisement

Koa & Passport Missing credentials

I have a Koa server that uses Passport to authenticate users against an Array, and a React client. After successful login, the following requests are not authenticated as the cookie is undefined. The authenticate function’s error parameter has:

{ message: 'Missing credentials' }

After browsing the site, I fixed the usual errors, calling the returned function of authenticate, adding {credentials: 'include'} to fetch etc, but still I have the same problem.

Middleware list: router.use(cookie.default());

app.use :

koa-body, koa-session-store (also tried with koa-session), passport.initialize(), passport.session(), router.routes(), koa-static

local strategy

passport.use(new Strategy((username,password,callback)=>{
    var u =  users.find(u=>u.username == username);
    return (u  && password == 'password')?  callback(null, u ):callback('user not found', false);
}));

/login authenticate

.post('/login', (ctx)=>{
    console.log(ctx.request.body);
    return passport.authenticate('local',(err,user,info,status)=>{
        if(user) {
            ctx.login(user);
            ctx.body = {success: true}; // works correctly
            ctx.redirect('/login-success'); 
        } else {
            ctx.redirect('/login-failure');
        }
    })(ctx);
});

/login-success

router.get('/login-success',async(ctx)=> {
    return passport.authenticate('local',(err,user,info,status)=>{
        console.log(err); // "Missing credentials"
    })(ctx);
    await ctx.response;
    ctx.body = {success: true};
}).

Client call

let body = JSON.stringify({username: this.state.username, password: this.state.password});
let result = await fetch('http://localhost:4200/login',{method:'POST',credentials: 'include',body, headers:{'Content-Type':'application/json'}});

Advertisement

Answer

The fix is actually simple, but the reason is hard to find.

async middleware must either call await next() or return next() at the end. Otherwise a 404 error is caused.

Adding await next() to the async /login-success callback, fixed the issue.

Documentation: https://github.com/koajs/koa/blob/master/docs/troubleshooting.md#my-middleware-is-not-called

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement