【发布时间】: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