how to handle cache in express with redis as middleware - node.js

I have a question.
I am using express 4 and to host my services and my client (angular pages).
I want to add Redis middleware in order to cache response of requests.
I know there are modules which cache request according to user session
but my situation is a bit different.
Because I want to cache result of all the requests from specific tenant.
one tenant can have multiple users,
In my authentication process I can find out if the specific request belong to the same tenant or not.
As already figured out I have multi-tenant application
Any suggestions how to approach this problem ?

A bit tardy, but you can check module express-redis-cache (disclosure, I am the author). It should allow you enough flexibility.

Related

Share session between two node apps

I have a node application that's using passport-local-mongoose for authentication. I have a second node app that's served in an iframe of the first app. I'd like to protect the express routes in the second app with the same session of the first app so that the user only logs in once, but the express routes in the second app are still protected. Is there a way for the two node apps to share a session? Or perhaps there is another approach?
Thank you.
The easiest way I can think of would be to simply store sessions in MongoDB. Then your second app's middleware could check the session passed in the request against the same database. The downside of this approach is that you have to implement some of the same authentication logic in 2 places.
Perhaps even better, you could build a 3rd microservice that handles authentication specifically. That would basically wrap your session store and centralize the authentication logic in one place. Both of the other 2 apps would then consume this service. This is an area I'm still learning about personally, and this site has been helpful: https://dejanglozic.com/2014/10/07/sharing-micro-service-authentication-using-nginx-passport-and-redis/.

NodeJS/express - security for public API endpoint

I'm developing my web-site project based on NodeJs/Express, and for some UI parts I'm using Jquery ajax request to fetch secondary data.
How can we handle some basic control on our Rest API end-points that are used for ajax calls by the browser?
I was thinking about some kind of token authorization , but it can be also used by other clients (scripts etc.) once it has been intercepted , so how can we protect our server from unwanted requests? What other controls should be used in this cases (recognize too many request from same client, clients black list,etc)?
There are three main topics Authentication, Authorization, Security. I will give links and only shortly answers. Subject is enough big to write few books.
Authentication - who is the one who is making request. There are many 'strategies' to authentication user. Please check most pupular module for this : http://passportjs.org/docs.
Of course you can inplement one or more of this strategies alone.
For stateless authentication jwt tokens are very convenient. If you want to code it yourself (Passport has this strategy) check this link (one of many in web) https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens.
How to prevent from token interception? Use always https and set token expiration time short.
Where to store your token client side? for detail look at this https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/ In short don't store in web storage because of XSS attacks. Use cookies, when they are correctly configured they are safe (more in attached link), if not configured they are very exposed to threats.
Authorization : we know user, but he has access only to some resources. Please check https://github.com/OptimalBits/node_acl
There is gist with node_acl and passport : https://gist.github.com/danwit/e0a7c5ad57c9ce5659d2
In short passport authenticate user. We now who want what. We setup roles and resources and define roles and resources relation. Then we set for each user roles. Module will check for us user permission.
Security: please look for this subject in documentation of sails framework http://sailsjs.org/documentation/concepts/security they describes attacks and how framework prevent form them. I write about express:
DDOS: (part of your question "too many request from same client") "At the API layer, there isn't much that can be done in the way of prevention". This is subject most for servers admins. In short use load balancer. If it is one IP (not hundreds) then blacklist or deley response (for start look at this https://www.npmjs.com/package/delayed-request but I thing that solution must be more sophisticated).
CSRF: "type of attack which forces an end user to execute unwanted actions on a web application backend". Look at this module https://www.npmjs.com/package/csrf
XSS: "type of attack in which a malicious agent manages to inject client-side JavaScript into your website" don't trust any data from user. Always validate, filter, santize. Look at this https://www.npmjs.com/package/xss
In documentation of sails, there is more attack types but above are most popular.
Use express session + passport (http://passportjs.org/)
Basically you should have a login to the website and than only authenticated users can call the REST apis.
now... if you don't want a login, than you can't really protect the APIs as the website by design is open.
You didn't specify much info so it is hard to say more than that.
Also DoS attacks can't be protected by your code, and usually its not the responsibility of the app server (in your case node.js express) to provide such protection. If someone wants your website down by doing DoS attacks, than without other layers (see https://en.wikipedia.org/wiki/Denial-of-service_attack#Defense_techniques) which mostly mean it is up to a router/switch/so on... to implement.

SPA security using Backbone.js, Require.js and Laravel

I'm currently searching the best way for developing my next webapplication. I'm thinking about using Backbone.js and build a single page application. But I really can't imagine how to secure my app since nearly everything is done on client side. Of course I just could prevent the users from accessing my RESTful Api so they would not have access to my data. But all the view/model/collection/template js files are still accessible.
Or is there a known way to serve the js files with php (laravel), which would allow me to only serve the files I need for the respective user.
I just couldn't find a solution by searching the Web. But I just don't think that I am the lonely person who needs a clean and secure authentication method including different user rights.
Thank you in advance!
Your backend application will fetch data from a backend (= API), and probably send back some changes.
This code can't have "security holes / leaks" as long as your backend is secured.
If you are afraid of people stealing your code, you can always minify the JS (check grunt.js and almond.js for this)
To secure your backend you can make use of Laravel's auth class, and the auth filter as mentioned before.
Besides normal auth, you could implement roles, that you can assign to specific users, giving them more or less access to certain resources in your backend.
Here's the method I would try :
Separate the application in two parts.
One part - login via regular Laravel Auth on a separate page, and then when the user is logged in serve the single page app in a different view.
Wouldn't this work?
Web Services are no different than any other web application you build. At the end of the day you are exposing functionality to the client (which is also the attacker). It doesn't matter what the client is implemented in, if you expose dangerous functionality you will be hacked.
Have a session state, keep track of the user id and make sure that the user is only accessing resources they have been allowed to access.
I do not think that what JS/template files are exposed really matters. Essentially, you should only be allowing data interaction to authenticated users. Think of this as two separate applications.
The front-end application logs in, and a cookie is stored (or some other persistence is used).
The back-end application then uses the persistent authentication to validate every single user request for data, and every user action.
This way you don't have to worry about the security, the client can only fetch the data that the server allows it to, and, likewise, it can only interact with the data insofar as the server allows it. You shouldn't be relying on the client side for security anyway, even logged in, otherwise some malicious user could, conceivably, save all your frontend code and use it against you without authentication.

Simply Handling Session Free Node.js with Authentication and Client Side Templating

I have a question - I found a few answers floating around here.
Basically, I want to have a node.js server application serving up json documents for requests.
All templating will happen client side
Some of the requests will require authentication but most will not.
I'd like to eliminate the need for framework (express) session management wherever possible (as recommended by linked-in) to improve performance so I thought of a couple solutions for authentication.
1) Write custom authentication that persists the session as a document and checks it wherever a request is made to the node.js server that needs authentication. Keep all user info in html5 storage or cookies for the dom to use for templating.
+ Works
- Have to write custom security to avoid session management in express/node.
2) Have 2 node.js instances. One serves everything in the public domain. One is for secure requests only. Still keep all user info in the session.
+ Simple as we can push session management onto the framework for requests that require authentication
- Has 2 node instances. May have some bad DRY.
Is the second option reasonable? Or is there another option I'm missing. Option 1 is my fallback as I'd rather not do all of the custom coding when it's already built into express.
EDIT:
To leave one possibility on here, I think I can use multiple callbacks on a resource request to allow an interceptor type pattern for validating user in session. This answers the first question.
From the express documentation:
Several callbacks may also be passed, useful for re-using middleware that load resources, perform validations, etc.
app.get('/user/:id', user.load, function(){
// ...
})

Single page applications, http or websockets, is connect/express done for?

This is a question involving single page web apps and my question is in bold.
WARNING:
I'm hardly an expert on this subject and please correct me if I'm wrong in part of my understanding of how I think HTTP and WebSockets work.
My understanding of how HTTP restful APIs work is that they are stateless. We use tools like connect.session() to interject some type of state into our apps at a higher level. Since every single request is new, we need a way to re-identify ourself to the server, so we create a unique token that gets sent back and forth.
Connect's session middleware solves this for us in a pretty cool way. Drop it into your middleware stack and you have awesome-sauce sessions attached to each request for your entire application. Sprinkle in some handshaking and you can pass that session info to socket.io fairly easily, even more awesome. Use a RedisStore to hold the info to decouple it from your connect/express app and it's even more awesome. We're talking double rainbow awesome here.
So right now you could in theory have a single page application that doesn't depend on connect/sessions because you don't need more than 1 session (initial handshake) when it comes to dealing with websockets. socket.io already gives you easy access to this sessionId, problem solved.
Instead of this authentication work flow:
Get the email and password from a post request.
Query your DB of choice by email to get their password hash.
Compare the hashes.
Redirect to "OK!" or "NOPE!".
If OK, store the session info and let connect.session() handle the rest for the most part.
It now becomes:
Listen for a login event.
Get the email and password from the event callback.
Query your DB of choice by email and get their password hash.
Compare the hashes.
Emit an "OK!" or "NOPE!" event.
If OK, do some stuff I'm not going to think of right now but the same effect should be possible?
What else do we benefit from by using connect? Here's a list of what I commonly use:
logger for dev mode
favicon
bodyparser
static server
passport (an authentication library that depends on connect/express, similar to what everyauth offers)
The code that loads the initial single page app would handle setting up a static server and favicon. Something like passport might be more tricky to implement but certainly not impossible. Everything else that I listed doesn't matter, you could easily implement your own debug logger for websockets.
Right now is there really anything stopping us from having a single http based index.html file that encapsulates a websocket connection and doesn't depend on connect at all? Would socket.io really be able to make that type of application architecture work without setting up your own HTTP restful API if you wanted a single page app while offering cross brower support through its auto-magical fallbacks?
The only real downside at this point is caching results on the client right? Couldn't you incorporate local storage for that? I think creating indexable/crawlable content pages for search engines wouldn't be THAT big of a deal -- you would basically create a tool that creates static html files from your persistent database right?
Check out Derby and SocketStream.
I think what you're asking for is if it is plausible (using socket.io) to create a website that is a single static page with dynamically changing content.
The answer is "yes", it can work. Several node.js web frameworks already do this although I don't know of any that use socket.io.

Resources