简体   繁体   English

Passport-Azure-Ad似乎异步运行

[英]Passport-Azure-Ad seems to run asynchronously

I am using TSED - TypeScript Express Decorators ( https://tsed.io ) and it replaces express code like: 我正在使用TSED-TypeScript Express Decorators( https://tsed.io ),它替换了像以下这样的快速代码:

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

With an annotated middleware class - https://tsed.io/docs/middlewares.html 带有注释的中间件类-https: //tsed.io/docs/middlewares.html

So now the call to passport.authenticate() is in the use() method like: 因此,现在可以use()方法来调用passport.authenticate() ,例如:

@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) || {};
        this.authService.authenticate(request, response, next);  // <-- HERE
        if (!request.isAuthenticated()) {
            throw new Forbidden('Forbidden');
        }
        next();
    }
}

And then my AuthService.authenticate() is 然后我的AuthService.authenticate()

authenticate(request: express.Request, response: express.Response, next: express.NextFunction) {
    console.log(`before passport authenticate time: ${Date.now()}`);
    Passport.authenticate('oauth-bearer', {session: false})(request, response, next);
    console.log(`after passport authenticate time : ${Date.now()}`);

}

My passport configuration is performed in this same AuthService class: 我的护照配置在同一AuthService类中执行:

@Service()
export class AuthService implements BeforeRoutesInit, AfterRoutesInit {
    users = [];
    owner = '';

    constructor(private serverSettings: ServerSettingsService,
                @Inject(ExpressApplication) private  expressApplication: ExpressApplication) {
    }

    $beforeRoutesInit() {
        this.expressApplication.use(Passport.initialize());
    }

    $afterRoutesInit() {
        this.setup();
    }

    setup() {
        Passport.use('oauth-bearer', new BearerStrategy(jwtOptions, (token: ITokenPayload, done: VerifyCallback) => {
            // TODO - reconsider the use of an array for Users
            const findById = (id, fn) => {
                for (let i = 0, len = this.users.length; i < len; i++) {
                    const user = this.users[i];
                    if (user.oid === id) {
                        logger.info('Found user: ', user);
                        return fn(null, user);
                    }
                }
                return fn(null, null);
            };

            console.log(token, 'was the token retrieved');

            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;
                    const val = done(null, token);
                    console.log(`after strategy done authenticate time: ${Date.now()}`)
                    return val;
                }
                this.owner = token.oid;
                const val = done(null, user, token);
                console.log(`after strategy done authenticate time: ${Date.now()}`);
                return val;
            });
        }));
    }

This all works - My Azure configuration and setup for this logs in and retrieves an access_token for my API, and this token successfully authenticates and a user object is placed on the request. 所有这些都有效-我的Azure配置和设置为此登录并检索我的API的access_token,并且此令牌成功进行身份验证,并且将用户对象放置在请求中。

HOWEVER Passport.authenticate() seems to be asynchronous and doesn't complete until after the test for request.isAuthenticated() . 但是Passport.authenticate()似乎是异步的,直到对request.isAuthenticated()进行测试之后才能完成。 I have put in timing comments as can be seen. 可以看到,我发表了时间评论。 The after passport authenticate time: xxx happens 2 milliseconds after the before one. after passport authenticate time: xxx发生after passport authenticate time: xxx before 2毫秒之后。

And the after strategy done authenticate time: xxx one happens a second after the after passport authenticate time: xxx one. 而后after strategy done authenticate time: xxxafter passport authenticate time: xxx发生了一秒钟。

So it looks like Async behaviour to me. 所以对我来说,它看起来像是异步行为。

Looking in node_modules/passport/lib/middleware/authenticate.js ( https://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js ) there are no promises or async mentioned. node_modules/passport/lib/middleware/authenticate.jshttps://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js )时,没有提到任何承诺或异步。 However in node_modules/passport-azure-ad/lib/bearerstrategy.js ( https://github.com/AzureAD/passport-azure-ad/blob/dev/lib/bearerstrategy.js ) is an async.waterfall : 但是在node_modules/passport-azure-ad/lib/bearerstrategy.jshttps://github.com/AzureAD/passport-azure-ad/blob/dev/lib/bearerstrategy.js )中是async.waterfall

/*
 * We let the metadata loading happen in `authenticate` function, and use waterfall
 * to make sure the authentication code runs after the metadata loading is finished.
 */
Strategy.prototype.authenticate = function authenticateStrategy(req, options) {
  const self = this;
  var params = {};
  var optionsToValidate = {};
  var tenantIdOrName = options && options.tenantIdOrName;

  /* Some introduction to async.waterfall (from the following link):
   * http://stackoverflow.com/questions/28908180/what-is-a-simple-implementation-of-async-waterfall
   *
   *   Runs the tasks array of functions in series, each passing their results 
   * to the next in the array. However, if any of the tasks pass an error to 
   * their own callback, the next function is not executed, and the main callback
   * is immediately called with the error.
   *
   * Example:
   *
   * async.waterfall([
   *   function(callback) {
   *     callback(null, 'one', 'two');
   *   },
   *   function(arg1, arg2, callback) {
   *     // arg1 now equals 'one' and arg2 now equals 'two'
   *     callback(null, 'three');
   *   },
   *   function(arg1, callback) {
   *     // arg1 now equals 'three'
   *     callback(null, 'done');
   *   }
   * ], function (err, result) {
   *      // result now equals 'done'    
   * }); 
   */
  async.waterfall([

    // compute metadataUrl
    (next) => {
      params.metadataURL = aadutils.concatUrl(self._options.identityMetadata,
        [
          `${aadutils.getLibraryProductParameterName()}=${aadutils.getLibraryProduct()}`,
          `${aadutils.getLibraryVersionParameterName()}=${aadutils.getLibraryVersion()}`
        ]
      );

      // if we are not using the common endpoint, but we have tenantIdOrName, just ignore it
      if (!self._options._isCommonEndpoint && tenantIdOrName) {
          ...
      ...
      return self.jwtVerify(req, token, params.metadata, optionsToValidate, verified);
    }],

    (waterfallError) => { // This function gets called after the three tasks have called their 'task callbacks'
      if (waterfallError) {
        return self.failWithLog(waterfallError);
      }
      return true;
    }
  );
};

Could that cause async code? 会导致异步代码吗? Would it be a problem if run in 'normal express Middleware'? 如果在“普通表达中间件”中运行会不会有问题? Can someone confirm what I've said or to deny what I've said and to provide a solution that works. 有人可以确认我所说的话还是拒绝我所说的话并提供可行的解决方案。


For the record I started asking for help on this Passport-Azure-Ad problem at my SO question - Azure AD open BearerStrategy "TypeError: self.success is not a function" . 作为记录,我开始在我的SO问题-Azure AD open BearerStrategy“ TypeError:self.success不是一个函数”上寻求有关Passport-Azure-Ad问题的帮助。 The problems there seem to have been solved. 那里的问题似乎已经解决了。


Edit - the title originally included 'in TSED framework' but I believe this problem described exists solely within passport-azure-ad . 编辑 -标题最初包含在“ TSED框架中”,但我相信所描述的问题仅存在于passport-azure-ad

This is a solution to work around what I believe is a problem with passport-azure-ad being async but with no way to control this. 这是解决我认为passport-azure-ad异步但无法控制的问题的解决方案 It is not the answer I'd like - to confirm what I've said or to deny what I've said and to provide a solution that works. 这不是我想要的答案-确认我的发言或拒绝我的发言并提供有效的解决方案。

The following is a solution for the https://tsed.io framework. 以下是https://tsed.io框架的解决方案。 In https://github.com/TypedProject/ts-express-decorators/issues/559 they suggest not using @OverrideMiddleware(AuthenticatedMiddleware) but to use a @UseAuth middleware. https://github.com/TypedProject/ts-express-decorators/issues/559中,他们建议不要使用@OverrideMiddleware(AuthenticatedMiddleware)而应使用@UseAuth中间件。 It works so for illustration purposes that is not important here (I will work through the feedback shortly). 这样做是出于说明目的,在这里并不重要(我将很快处理反馈)。

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

    // NO THIS VERSION DOES NOT WORK.  I even removed checkForAuthentication() and
    // inlined the setInterval() but it made no difference
    // Before the 200 is sent WITH content, a 204 NO CONTENT is

    // HAD TO CHANGE to the setTimeout() version
    // async checkForAuthentication(request: express.Request): Promise<void> {
    //     return new Promise<void>(resolve => {

    //         let iterations = 30;
    //        const id = setInterval(() => {
    //             if (request.isAuthenticated() || iterations-- <= 0) {
    //                 clearInterval(id);
    //                 resolve();
    //             }
    //         }, 50);
    //     });
    // }

    // @async
    public use(
        @EndpointInfo() endpoint: EndpointMetadata,
        @Request() request: express.Request,
        @Response() response: express.Response,
        @Next() next: express.NextFunction
    ) {
        const options = endpoint.get(AuthenticatedMiddleware) || {};
        this.authService.authenticate(request, response, next);

        // AS DISCUSSED above this doesn't work
        // await this.checkForAuthentication(request);
        // TODO - check roles in options against AD scopes
        // if (!request.isAuthenticated()) {
        //     throw new Forbidden('Forbidden');
        // }
        // next();

        // HAD TO USE setTimeout()
        setTimeout(() => {
            if (!request.isAuthenticated()) {
                console.log(`throw forbidden`);
                throw new Forbidden('Forbidden');
            }
            next();
        }, 1500);
}

Edit - I had a version that used setInterval() but I found it didn't work. 编辑 -我有一个使用setInterval()的版本,但是我发现它不起作用。 I even tried inlining the code in to the one method so I could remove the async . 我什至尝试将代码内联到一个方法中,以便删除async It seemed to cause the @Post the UserAuthMiddleware is attached to, to complete immediately and return a 204 "No Content". 似乎导致UserAuthMiddleware附加到@Post ,立即完成并返回204“无内容”。 The sequence would complete after this and a 200 with the desired content would be returned but it was too late. 此序列将在此之后完成,并且将返回具有所需内容的200,但是为时已晚。 I don't understand why. 我不明白为什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM