nest: [Passport] Custom callback in Passport Middleware for error handler

Some errors types as invalid signature, jwt expired, no auth token, invalid token, invalid algorithm… are not being handled on passport-jwt

The default response send only ‘unauthorized’ message and http status 401

In this Issue the author recommend using custom callbacks according to official passport docs

I’ve tried to try the following code, but I can not get it to work fine

export class AuthModule implements NestModule {
  public configure(consumer: MiddlewaresConsumer) {
    consumer
      .apply(passport.authenticate('jwt', { session: false }, (err, user, info) => {
        console.log(info.message)
      }))
      .forRoutes({ path: '/auth/authorized', method: RequestMethod.ALL });
  }
}

console.log(info.message) Is printed but does not can exit function, and within it next() function is not available, so response stays in the waiting forever

Any idea?

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 1
  • Comments: 21 (4 by maintainers)

Most upvoted comments

hi,

you can access next like this.

@Middleware()
export class LocalStrategyMiddleware implements NestMiddleware {
    resolve() {
        return async (req, res, next) => {
            return await passport.authenticate('local', {session: true}, (err, user, info) => {
                if (err) {
                    next(new HttpException(err, 401));
                }
                else {
                    next();
                }
            })(req, res, next)
        }
    }
}

Hi @cdiaz, Just use class middleware, not the functional one.