10

I'm trying to use this library (keycloak-connect) for authentication and authorization. It has a global middleware that can be directly used by app.use() method or by wrapping a nestjs middlewareclass around it. But how to use the route specific express middleware which is used to protect individual routes?.

Example usage in plain express app

app.get( '/protected', keycloak.protect('adminRole'), handler );

The protect method returns a plain express middleware with signature function(req, res, next)

Abhinandan N.M.
  • 362
  • 1
  • 3
  • 15

2 Answers2

15

Your "handler" is a method (decorated with either GET, or POST, etc) in a class decorated with @Controller. The module importing this controller is supposed to declare the middleware.

Example:

@Module({
  controllers: [YourController],
})
export class YourModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(keyCloack.protect('adminRole'))
      .forRoutes('/protected');
  }
}

Where YourController contains the handler for the route '/protected'.

Implementing NestModule is the key. Then you're obliged to declare configure and can use the consumer.

VinceOPS
  • 2,602
  • 18
  • 21
  • 2
    Where do you get the keyCloack instance from? Shoudn't it be possible to integrate it into an @AuthGuard? A link to an example keycaloak + naestjs setup would be much appreciated. – Biel Simon Mar 21 '20 at 23:33
  • 1
    I don't know this library, sorry, I reused `keyCloack` because it was provided "as is" in the OP's code. However, I assume that you can create a custom provider for it, and register/export it in a custom/dedicated `@Module`. See "Dependency Injection" in the NestJS documentation. Modules and Guards can inject providers too. Thus, the example of `YourModule` I gave could have a constructor like `constructor(@Inject(KEYCLOACK) private keyCloack: SomeType) {}` and use `this.keyCloack` in its method. The same is true for a Guard. – VinceOPS Mar 22 '20 at 11:18
2

In case you only want your middleware to be applied on the routes in a controller, you may -

export class AppModule implements NestModule {
 configure(consumer: MiddlewareConsumer) {
 consumer
  .apply(LoggerMiddleware)
  .forRoutes(CatsController);
 }
}
Kshateesh
  • 571
  • 1
  • 8
  • 21