【问题标题】:How to encapsulate Koa-Passport?如何封装 Koa-Passport?
【发布时间】:2019-01-14 22:45:54
【问题描述】:

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

我使用 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);
};

【问题讨论】:

    标签: passport.js koa2 koa-router koa-passport


    【解决方案1】:

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

    koa-passport

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

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

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

    【讨论】:

      猜你喜欢
      • 2018-09-22
      • 2020-01-20
      • 2016-10-03
      • 1970-01-01
      • 2021-01-14
      • 2020-05-02
      • 1970-01-01
      • 2014-12-25
      • 2023-03-25
      相关资源
      最近更新 更多