Passport-Azure-Ad似乎异步运行 [英] Passport-Azure-Ad seems to run asynchronously

查看:81
本文介绍了Passport-Azure-Ad似乎异步运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用TSED-TypeScript Express装饰器( https://tsed.io ),它取代了像:

I am using TSED - TypeScript Express Decorators (https://tsed.io) and it replaces express code like:

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

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

With an annotated middleware class - https://tsed.io/docs/middlewares.html

现在调用 passport.authenticate() use()方法中,例如:

So now the call to passport.authenticate() is in the use() method like:

@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();
    }
}

然后是我的 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()}`);

}

我的护照配置是在同一AuthService类中执行的:

My passport configuration is performed in this same AuthService class:

@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;
            });
        }));
    }

所有方法均有效-我的Azure配置和设置为此登录并检索我的API的access_token,此令牌成功通过身份验证,并在请求上放置了用户对象。

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.

如何 Passport.authenticate()似乎是异步的,直到对 request.isAuthenticated()进行测试之后才能完成。可以看到,我发表了时间评论。护照认证后的时间:xxx 发生在之前的2毫秒之后。

HOWEVER Passport.authenticate() seems to be asynchronous and doesn't complete until after the test for 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.

完成策略后的身份验证时间:xxx 在完成护照后的身份验证时间:xxx 一个。

And the after strategy done authenticate time: xxx one happens a second after the after passport authenticate time: xxx one.

在我看来,这是异步行为。

So it looks like Async behaviour to me.

查看 node_modules / passport / lib / middleware / authenticate.js https://github.com/jaredhanson/passport/blob/master/lib/middleware/authenticate.js ),没有提到承诺或异步。但是在 node_modules / passport-azure-ad / lib / bearerstrategy.js https://github.com/AzureAD/passport-azure-ad/blob/dev/lib/bearerstrategy.js )是 async.waterfall

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. 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:

/*
 * 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.

作为记录,我开始在我的SO问题上寻求有关Passport-Azure-Ad问题的帮助-天蓝色的AD打开BearerStrategy TypeError:self.success不是一个功能

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". The problems there seem to have been solved.

编辑-最初包含在 TSED框架,但我认为所描述的问题仅存在于 passport-azure-ad 中。

Edit - the title originally included 'in TSED framework' but I believe this problem described exists solely within passport-azure-ad.

推荐答案

这是解决我认为 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. 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.

以下是 https://tsed.io 框架的解决方案。在 https://github.com/TypedProject/ts-express-decorators/issues / 559 ,他们建议不要使用 @OverrideMiddleware(AuthenticatedMiddleware),而应使用 @UseAuth 中间件。之所以如此,是出于说明的目的,在这里并不重要(我将很快处理反馈)。

The following is a solution for the https://tsed.io framework. In https://github.com/TypedProject/ts-express-decorators/issues/559 they suggest not using @OverrideMiddleware(AuthenticatedMiddleware) but to use a @UseAuth middleware. 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);
}






编辑-我有一个使用 setInterval()的版本,但是我发现它不起作用。我什至尝试将代码内联到一个方法中,以便删除 async 。它似乎导致 @Post UserAuthMiddleware 附加在一起,立即完成并返回204无内容 。此序列将在此之后完成,并且将返回具有所需内容的200,但是为时已晚。我不明白为什么。


Edit - I had a version that used setInterval() but I found it didn't work. I even tried inlining the code in to the one method so I could remove the async. It seemed to cause the @Post the UserAuthMiddleware is attached to, to complete immediately and return a 204 "No Content". The sequence would complete after this and a 200 with the desired content would be returned but it was too late. I don't understand why.

这篇关于Passport-Azure-Ad似乎异步运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆