我有一个 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'}});