0

也许这有一个非常简单的答案,但我的代码有些问题。这就是我想要做的。

我使用 koa-passport 创建了一个 koa2 应用程序,我想将 Passport 的使用封装在一个类 AuthAdapter 中(以下简称)。

class AuthAdapter {
    setup(koaApp) {
        koaApp.use(passport.initialize());

        passport.use('http-bearer', new PassportHttpBearerStrategy(function(token, done) {
            koaApp.log.info('passport: payload request', token);
            return done(null, { clientId: 1 });
        }));
    }

    async authroute(ctx, next) {
        return passport.authenticate('http-bearer', (error, user, info) => {
            if (error) {
                ctx.throw(500, 'Authentication Error');
            } if (!user) {
                ctx.throw(403, 'Authentication Forbidden');
            } else {
                ctx.log.debug('Passport-Route-Mw: auth ok', { user: user, info: info });
            }
        })(ctx, next);
    }
}

我有一个 API 类并声明了如下路由:

static _setupRoutes(koaApp, koaRouter) {
    koaRouter
        .get('getter', '/getter', koaApp.authAdapter.authroute, MyApi.myGetterMethod);
    koaApp
        .use(koaRouter.routes())
        .use(koaRouter.allowedMethods());
}

...我的API

static async myGetterMethod(ctx) {
   ...
}

现在的问题是: setup 和 setupRoutes 被正确调用。Passport verify 正在执行,authroute 方法也在执行。

我的问题是 myGetterMethod 不是。

我的怀疑是,通过封装passport.authenticate,“返回”没有按应有的方式运行。

那应该如何实施?等待?

更新:感谢下面的答案,确实是解决方案,所以我的方法最终是这样的:

async function authenticate(ctx, next) {
    // https://github.com/rkusa/koa-passport/issues/125#issuecomment-462614317

    return passport.authenticate('http-bearer', { session: false }, async(err, user, info) => {
        if (err || !user) {
            ctx.throw(401, 'passport-auth: user unauthenticated');
        }

        await next();
    })(ctx);
};
4

1 回答 1

2

我认为您需要在回调中调用,因为当您提供自定义回调时next,koa-passport 将停止调用next

koa-护照

第 94 行:调用自定义回调将始终调用resolve(false)

第 149 行:if resolve(cont !== false) call next

结果,使用自定义回调将停止链。你需要next在你的回调中调用。

于 2019-04-22T17:07:11.697 回答