如何在nestjs中间件中使用护照?

时间:2018-02-27 15:27:52

标签: node.js typescript nestjs

我正在尝试编写身份验证中间件。问题是,每当我尝试做某事时,我的设置都会抛出“Unauthenticated”。

我的中间件:

@Middleware()
export class AuthMiddleware implements NestMiddleware {
  constructor(
    @Inject(constants.logger) private logger: Winston,
  ){}

  resolve(...args: any[]): ExpressMiddleware {
    return passport.authenticate('jwt', { session: false });
  }
}

JwtStrategy类:

@Component()
export class JwtStrategy extends Strategy {
  constructor(
    private readonly authService: AuthService,
    @Inject(constants.config) private readonly config: Config,
  ) {
    super(
      {
        jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
        passReqToCallback: true,
        secretOrKey: config.JWT_SECRET,
      },
      async (req, payload, next) => {
        console.log('hello from verifycb');
        next(null, payload);
      },
    );
    passport.use('jwt', this);
  }

  public async verify(req, payload: TokenData, done) {
    console.log('JwtStrategy::verify(req, payload)', {req, payload});
    const isValid = await this.authService.isUserValid(payload);
    if (!isValid) {
      return done('Unauthorized 22', false);
    }
    done(null, payload);
  }
}

我确定我的中间件叫。我是以奇怪的方式使用它还是什么?

1 个答案:

答案 0 :(得分:1)

可能会有点迟,但您需要在模块

中明确consume 中间件

// active.module.ts

@Module({
    ...
})
export class ActiveModule implements NestModule {
    public configure(consumer: MiddlewaresConsumer) {
        consumer.apply(JwtMiddleware).forRoutes(
            {path: '/api/lists/create', method: RequestMethod.POST}
        );
    }
}

在此示例中,JwtMiddleware是我的中间件,与您的AuthMiddleware相同。

// active.controller.ts

@Controller('lists')
export class ActiveController {
    @Post('create')
    async create(@Req() request: Request) {
         // req.user will be available for you
    }
}