Reputation: 145
For the NodeJS application we are developing, I want to process cookies and also check the role of users for each request. I have implemented this using filters when I was coding for Tomcat Servlets, how do I implement similar architecture when coding for NodeJS?
Upvotes: 3
Views: 4525
Reputation: 17094
The Node equivalent of Servlet filters is Connect/Express middlewares, which have access to the request and response objects, can set headers on the response and decide whether to forward request to the next middleware in the chain of middlewares.
Just as the doFilter
method is invoked with 3 arguments, a middleware is also invoked with 3 arguments, but instead of calling filterChain.doFilter
to forward the request, you call the next
callback. The results of not calling the next
callback is the same as not calling filterChain.doFilter()
: they'll both block the request unless the response is end
ed.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) {
if(isAuthorised(request) chain.doFilter(request, response);
}
function aMiddleware (req, res, next/*filterChain*/) {
if(isAuthorised(req)) next();
}
Upvotes: 6
Reputation: 10145
Assuming you use express, express middleware is similar to filters:
http://expressjs.com/api.html#middleware
But, if you are looking specifically for auth, Passport is a more complete solution: http://passportjs.org/guide/
Upvotes: 2