【问题标题】:Koa & Passport Missing credentialsKoa & Passport 缺少凭据
【发布时间】:2022-02-10 23:19:26
【问题描述】:

我有一个 Koa 服务器,它使用 Passport 针对数组对用户进行身份验证, 和一个 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'}});

【问题讨论】:

    标签: javascript node.js cookies koa koa-passport


    【解决方案1】:

    解决方法其实很简单,但原因很难找到。

    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-called

    【讨论】:

      猜你喜欢
      • 2019-03-02
      • 2020-12-19
      • 2015-07-20
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 2020-09-26
      • 2013-03-06
      相关资源
      最近更新 更多