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)
Middleware is a function which is called before the route handler. Middleware functions have access to the request and response objects, and the next() middleware function in the application's request-response cycle. The next middleware function is commonly denoted by a variable named next .
In this pa- per we present Interceptor, a middleware-level application segregation and scheduling system that is able to strictly en- force quantitative limitations on node resource usage and, at same time, to make P2P applications achieve satisfactory performance even in face of these limitations.
NestJS is platform agnostic - it uses Express by default but you can configure it to work with any HTTP framework like Fastify. It provides a wide range of functionalities, APIs, and libraries so that developers can build applications with fewer lines of code.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With