3

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

我的中间件:

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

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

4

1 回答 1

2

可能有点晚了,但您需要在模块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
    }
}
于 2018-04-11T19:01:41.947 回答