Azure AD打开BearerStrategy“ TypeError:self.success不是函数”

时间:2019-05-30 05:49:32

标签: azure azure-active-directory passport.js

我在https://github.com/AzureAD/passport-azure-ad/issues/427询问了此消息,但没有回应。我觉得这是一个错误,使我无法完成自己的工作,因此我走得越来越远才能得到答案。是我在做的事还是错误?

我写的问题与以前有所不同,因为我对该问题进行了更多调查(我将指出差异的出处)。

Passport-Azure-AD版本4.1.0-https://www.npmjs.com/package/passport-azure-ad#52-bearerstrategy

我已经根据文档进行了设置:

setup() {
    const findById = (id, fn) => {
        for (let i = 0, len = this.users.length; i < len; i++) {
            const user = this.users[i];
            if (user.sub === id) {
                logger.info('Found user: ', user);
                return fn(null, user);
            }
        }
        return fn(null, null);
    };

    this.bearerStrategy = new BearerStrategy(jwtOptions,
        (token: ITokenPayload, done: VerifyCallback) => {  
            findById(token.oid, (err, user) => {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    // 'Auto-registration'
                    logger.info('User was added automatically as they were new. Their oid is: ', token.oid);
                    this.users.push(token);
                    this.owner = token.oid;
                    return done(null, token);
                }
                this.owner = token.oid;
                return done(null, user, token);
            });
        }
    );
    console.log(`setup bearerStrategy`);
}

我使用的jwtOptions是:

选项如下:

const jwtOptions = {
    identityMetadata: 'https://login.microsoftonline.com/xyz/v2.0/.well-known/openid-configuration',
    clientID: '0123456789',
    loggingLevel: 'info',
    loggingNoPII: false,
    passReqToCallback: false
};

并使用以下命令(从中间位置)运行身份验证:

authenticate(request: express.Request) {
    this.bearerStrategy.authenticate(request, {session: false});
}

注意,这与doco有所不同,因为他们的内容不起作用。

它在行上失败:

 return done(null, token);

使用:

[2019-05-29T13:49:33.479] [INFO ] [AUTHSERVICE_LOGGER] - User was added automatically as they were new. Their oid is:  123

.../translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:565
        return self.success(user, info);
                    ^
TypeError: self.success is not a function
    at verified (/Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:565:21)
    at findById (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:106:32)
    at findById (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:87:20)
    at Strategy.bearerStrategy.passport_azure_ad_1.BearerStrategy [as _verify] (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:97:17)
    at jwt.verify (/Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:363:19)
    at /Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/jsonWebToken.js:80:16
    at process._tickCallback (internal/process/next_tick.js:61:11)

此处与原始帖子相比有所不同

如果我在代码中放置了一个断点,则BearerStrategy.js中的self对象的错误是:

{
  "name": "oauth-bearer",
  "_options": {
    "identityMetadata": "https://login.microsoftonline.com/xyz/v2.0/.well-known/openid-configuration",
    "clientID": "0123456789",
    "loggingLevel": "info",
    "loggingNoPII": false,
    "passReqToCallback": false,
    "clockSkew": 300,
    "validateIssuer": true,
    "allowMultiAudiencesInToken": false,
    "audience": [
      "1234",
      "spn:1234"
    ],
    "isB2C": false,
    "_isCommonEndpoint": false,
    "_verify" = (token, done) => {...},
    "__proto__" = Strategy(...,
  }
}

__proto__下是:

 authenticate = function authenticateStrategy(req, options) {
 constructor = function Strategy(options, verifyFn) {
 failWithLog = function(message) {
 jwtVerify = function jwtVerifyFunc(req, token, metadata, optionsToValidate, done) {
 loadMetadata = function(params, next) {

您可以看到Passport-Azure-Ad中没有success。它确实定义了failWithLog https://github.com/AzureAD/passport-azure-ad/blob/e9684341920ac8ac41c55a1e7150d1765dced809/lib/bearerstrategy.js#L600-他们忘了添加其他人吗?

护照定义了其他(https://github.com/jaredhanson/passport/blob/1c8ede35a334d672024e14234f023a87bdccaac2/lib/middleware/authenticate.js#L230),但是它们处于封闭状态,从不公开。也没有定义它们的父策略对象。与外部的唯一连接是通过公开的身份验证方法https://github.com/jaredhanson/passport/blob/1c8ede35a334d672024e14234f023a87bdccaac2/lib/middleware/authenticate.js#L70

但是,正如所见,Passport-Azure-Ad定义了它自己的身份验证方法(https://github.com/AzureAD/passport-azure-ad/blob/e9684341920ac8ac41c55a1e7150d1765dced809/lib/bearerstrategy.js#L372),并且从不调用passsport。

在我看来,它从未奏效。

任何人都可以确认或不同意吗?

我将更新https://github.com/AzureAD/passport-azure-ad/issues/427上的帖子以供参考。

接下来,我将转到git bisect存储库,看看是否可以找到以前定义的那些遗漏方法或其他突出之处的更改。

1 个答案:

答案 0 :(得分:0)

我可以确认在编写代码时它将永远无法工作。主要有两个问题:

通过参数

根据我对这个问题的评论,我忽略了在问题中提供信息,因为我认为这不相关。但这是

我正在使用TSED-TypeScript Express Decorators(https://tsed.io),它替换了诸如以下这样的明示中间件代码:

   server.get('/api/tasks', passport.authenticate('oauth-bearer', { session: false }), listTasks);

带有带注释的中间件类-https://tsed.io/docs/middlewares.html

所以现在passport.authenticate()的调用是在use()方法中,就像我之前展示的那样(这是不正确的):

@OverrideMiddleware(AuthenticatedMiddleware)
export class UserAuthMiddleware implements IMiddleware {
    constructor(@Inject() private authService: AuthService) {
    }

    public use(
        @EndpointInfo() endpoint: EndpointMetadata,
        @Request() request: express.Request,
        @Response() response: express.Response,
        @Next() next: express.NextFunction
    ) {
        const options = endpoint.get(AuthenticatedMiddleware) || {};
        Passport.authenticate('oauth-bearer', {session: false});  // <-- WRONG
        if (!request.isAuthenticated()) {
            throw new Forbidden('Forbidden');
        }
        next();
    }
}

我忽略的是表达中间件被传递给请求对象。所以我实际上需要拥有的是:

        Passport.authenticate('oauth-bearer', {session: false})(request, response, next);  // <-- CORRECT

必须使用Passport.use()

该文档具有误导性。鉴于我对Passport不太了解,所以我对此没有考虑太多。

doco(http://www.passportjs.org/packages/passport-azure-ad/)(位于5.2.1.1 Sample using the BearerStrategy)说要使用:

var bearerStrategy = new BearerStrategy(options,
  function(token, done) {
    log.info('verifying the user');
    log.info(token, 'was the token retreived');
    findById(token.oid, function(err, user) {
      if (err) {
        return done(err);
      }
      if (!user) {
        // "Auto-registration"
        log.info('User was added automatically as they were new. Their oid is: ', token.oid);
        users.push(token);
        owner = token.oid;
        return done(null, token);
      }
      owner = token.oid;
      return done(null, user, token);
    });
  }
);

我知道在描述其他策略时(例如同一页面上的5.1 OIDCStrategy):

passport.use(new OIDCStrategy({
    identityMetadata: config.creds.identityMetadata,
    clientID: config.creds.clientID,
    ...
  },
  function(iss, sub, profile, accessToken, refreshToken, done) {
    ...
  }
));

他们使用passport.use。我思考了一下差异(当我第一次看到它时)为1/2秒,并得出结论,鉴于登录是由Azure使用其AAD BearerStrategy库完成的,msal.js处理不同的事情。直到上述Fix#1不能解决问题,我才重新审视此问题。

我得出结论,TSED项目需要更新其文档/样本(我将为他们这样做);并且Passport Azure AD项目需要更新其doco。

仍然存在一些问题,我不知道是谁的错。我在Passport-Azure-Ad in TSED framework seems to run asynchronously上写道。