Rudolf
Rudolf

Reputation: 375

NestJs/Passport authentication doesn't work for routes passed asynchronously

When I pass selected routes from the database in the promise then the authourization doesn't work. That means the requests for passed routes are always authorized.

protected applyRoutes(consumer: MiddlewaresConsumer) {
    let paths = this.authPathService.findAll();

    paths.then((resultPaths) => {
        let result: {}[] = [];
        for (let path of resultPaths) {
            result.push({
                path: path.path,
                method: RequestMethod.ALL
            })
        }
        consumer
            .apply(passport.authenticate('jwt', { session: false }))
            .forRoutes(...result);

        return result;
    }, (error) => {
        console.log('error', error);
    });
}

It works well when i pass routes in an object array

protected applyRoutes(consumer: MiddlewaresConsumer) {
    consumer
        .apply(passport.authenticate('jwt', { session: false }))
        .forRoutes(...[
            { path: '/auth/authorized', method: RequestMethod.ALL },
            { path: '/auth/test', method: RequestMethod.ALL }]);

}

Upvotes: 0

Views: 1216

Answers (1)

Kamil Myśliwiec
Kamil Myśliwiec

Reputation: 9178

It's impossible to asynchronously apply middlewares using MiddlewaresConsumer. Instead, register an async component (https://docs.nestjs.com/fundamentals/async-components) that will fetch all paths, for example as AUTH_PATHS, then inject it to your module class, let's say AuthModule and use this array inside configure() method.

Upvotes: 1

Related Questions