0

我有一个 Koa 服务器,它使用 Passport 针对 Array 和一个 React 客户端对用户进行身份验证。成功登录后,以下请求未通过身份验证,因为 cookie 未定义。该authenticate函数的error参数有:

{ message: 'Missing credentials' }

浏览该网站后,我修复了通常的错误,调用返回的函数authenticate,添加{credentials: 'include'}fetch等,但我仍然有同样的问题。

中间件列表: router.use(cookie.default());

app.use

koa-body、koa-session-store(也尝试过 koa-session)、passport.initialize()、passport.session()、router.routes()、koa-static

地方战略

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);
}));

/登录验证

.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);
});

/登录成功

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};
}).

客户来电

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'}});
4

1 回答 1

0

修复其实很简单,但原因却很难找到。

async中间件必须要么调用await next()要么return next()在最后。否则会导致 404 错误。

添加await next()async /login-success回调,解决了这个问题。

文档:https ://github.com/koajs/koa/blob/master/docs/troubleshooting.md#my-middleware-is-not-call

于 2022-02-10T15:19:26.257 回答