Koa 护照认证

Koa Passport authenticate

我正在使用 Koa koa-passport, passport-local and koa-joi-router 制作一个简单的注册应用程序,它仅用于验证正文 json。示例建议像这样使用 passport.authenticate

router.route({
  method: 'post',
  path: '/signup',
  validate: {
    type: 'json',
    body: {
      username: Joi.string().required(),
      password: Joi.string().required()
    }
  },
  async handler(ctx, next) {
    const body: {
      username: string,
      password: string,
    } = ctx.request.body;

    try {
      await User.createAndSave(body.username, body.password);
      return passport.authenticate('local', async (error, user, info, status) => {
        if(error) {
          ctx.throw(500);
        } else if(user) {
          await ctx.login(user);
        } else {
          ctx.throw(400);
        }
      })(ctx, next);
    } catch {
      ctx.throw(500);
    }
  }
}

如您所见,我首先将用户输入我的数据库,然后调用 passport.authenticate 但奇怪的是,不要将用户的用户名或密码传递给它。那么该函数应该如何知道我希望它找到哪个用户呢?

经过一番查找,我发现在passport-local包中设置了用户名和密码正文字段名称。 Reference