How do I protect my App API from external exploitation? - node.js

I don't know if this is the right platform to ask this kind of question,
but I have an app that is separated between frontend (Angular) and backend/API (Nodejs). Now the API exposes public endpoints to be used by the frontend. Now how do I protect the API from being used or exploited by other parties and only keep it to my Angular app? I thought of using an HTTP only cookie but it seems its visible when someone opens the developer's tools on the request's headers.
I am completely out of ideas, thanks in advance.

There is no way to make your site 100% secure but you can slow attackers down, or convince them on to a less secure site if you cover the owasp top 10 and have some transport protection.
Transport protection
HTTPS: either use a solution with https already configured, like heroku or now.sh or use letsencrypt.org
Authentication - There are loads of solutions and you would need to figure out how important the data is you are trying to secure. JWT is a good starting point as it is the easiest and relatively secure.
OWASP attacks.
The OWASP top 10 is here:
https://www.owasp.org/images/7/72/OWASP_Top_10-2017_%28en%29.pdf.pdf
You can cover the majority of the list by using a library such as JOI, https://www.npmjs.com/package/joi and setting up the schemas so you only allow input that is absolutely necessary. Use whitelists of valid parameters rather than allow any string.
The only other precaution I would take is to use the npm library helmet, https://www.npmjs.com/package/helmet. This covers most of the XSS points
Those are probably the main points you need to cover, that will deter most opportunistic crackers

You can secure your API with a token using OAuth2, I don't know in angular to much but the best practice is to secure the nodejs with JWT Token.
Helpful link Creating an API authenticated with OAuth 2 in Node.js
Beer Locker: Building a RESTful API With Node - OAuth2 Server
--

Related

Authentication middleware in Express NodeJS - Best practice

I'm writing my first Express NodeJS app and I want to know what is the best practice when it comes to authentication middlewares?
I'm using access tokens and cookies (which are composed from user id and some random bytes) for each new user, and for some routes I want only given users to have access to it.
Is a good idea to access database from a middleware? Or where should I check if a given user has access to a given resource?
Thank you!
There are many modules built for authentication purpose for nodejs applications. However, the most commonly used module for nodejs/expressjs is Passport. If you wish to stay isolated from such libraries, nodejs has built-in libraries for encryption etc, for example, check this out.
For sessions and cookies, using signed cookies is always a good practice. Check out this SO post. There are many good practices for maintaining security (say, using https over http, token based authentication, etc.) followed throughout the development grounds, which you'll learn as you go on. Here is a short tutorial of JWT(JSON Web Tokens) for a good introduction to token based authentication in JSON you can check out.
Happy coding :)

JSON Web Token Auth Service - checking status on separate server to protect routes. NodeJS

For a project I’m working on currently I am developing an API using Node/Express/Mongo and separately developing a website using the same tools. Ideally I want to host these on separate servers so they can be scaled as required.
For authentication I am using jsonwebtoken which I’ve set up and I’m generally pleased with how it’s working.
BUT…
On the website I want to be able to restrict (using Express) certain routes to authenticated users and I’m struggling a little with the best way to implement this. The token is currently being saved in LocalStorage.
I think I could pass the token through a get parameter to any routes I want to protect and then check this token on the website server (obviously this means including the jwt secret here too but I don’t see a huge problem with that).
So my questions are
Would this work?
Would it mean (no pun intended) I end up with ugly URLs
Would I just be better hosting both on the same server as I could then save the generated token on the server side?
Is there a better solution?
I should say I don’t want to use Angular - I’m aware this would solve some of my problems but it would create more for me!
First off, I'll answer your questions directly:
Will this work? Yes, it will work. But there are many downsides (see below for more discussion).
Not necessarily. I don't really consider ugly urls to include the querystring. But regardless, all authentication information (tokens, etc.) should be included in the HTTP Authorization HEADER itself -- and never in the URL (or querystring).
This doesn't matter so much in your case, because as long as your JWT-generating code has the same secret key that your web server does, you can verify the token's authenticity.
Yes! Read below.
So, now that we got those questions out of the way, let me explain why the approach you're taking isn't the best idea currently (you're not too far off from a good solution though!):
Firstly, storing any authentication tokens in Local Storage is a bad idea currently, because of XSS (Cross Site Scripting attacks). Local Storage doesn't offer any form of domain limitation, so your users can be tricked into giving their tokens up quite easily.
Here's a good article which explains more about why this is a bad idea in easy-to-understand form: http://michael-coates.blogspot.com/2010/07/html5-local-storage-and-xss.html
What you should be doing instead: storing your JWT in a client-side cookie that is signed and encrypted. In the Node world, there's an excellent mozilla session library which handles this for you automatically: https://github.com/mozilla/node-client-sessions
Next up, you never want to pass authentication tokens (JWTs) via querystrings. There are several reasons why:
Most web servers will log all URL requests (including querystrings), meaning that if anyone gets a hold of these logs they can authenticate as your users.
Users see this information in the querystring, and it looks ugly.
Instead, you should be using the HTTP Authorization header (it's a standard), to supply your credentials to the server. This has numerous benefits:
This information is not typically logged by web servers (no messy audit trail).
This information can be parsed by lots of standard libraries.
This information is not seen by end-users casually browsing a site, and doesn't affect your URL patterns.
Assuming you're using OAuth 2 bearer tokens, you might craft your HTTP Authorization header as follows (assuming you're representing it as a JSON blob):
{"Authorization": "Bearer myaccesstokenhere"}
Now, lastly, if you're looking for a good implementation of the above practices, I actually wrote and maintain one of the more popular auth libraries in Node: stormpath-express.
It handles all of the use cases above in a clean, well audited way, and also provides some convenient middlewares for handling authentication automatically.
Here's a link to the middleware implementations (you might find these concepts useful): https://github.com/stormpath/stormpath-express/blob/master/lib/authentication.js
The apiAuthenticationRequired middleware, itself, is pretty nice, as it will reject a user's request if they're not authenticating properly via API authentication (either HTTP Basic Auth or OAuth2 with Bearer tokens + JWTs).
Hopefully this helps!

Ways to control authentication process in Node.js

I'm trying to build an API to control the user authentication processes in Node.js, just to exercise myself, but I'm not very familiar with the resources available at a Node.js environment.
The question being: what can I use to identify an user? Only thing I can think of now are cookies, but that don't seem very safe, imho. I thought maybe there's some variable in the http request I could use.
I do not want you to list JS libraries that handle authentications for me. I wanna try to build one myself.
You can implement your own code as an exercise, but the mechanism the code uses to establish authentication should exactly match existing common practice in the industry. Specifically you should use a session cookie, which needs to have many very specific properties in order to be secure. Cookies are secure enough in combination with a host of other best practices (https, server hardening, security patches, etc) for most web traffic. For enhanced security this is often combined with additional password prompts before important actions (amazon, yahoo), 2-factor authentication (google, github, etc), fraud detection heuristics (facebook, banking), etc. A cookie is precisely a "variable in the http request" as you say.

node.js REST api authentication and oauth2

I have several questions:
1) Is it a good practice to use REST API both for external API usage and as a server side for a backbone (or plain js) frontend?
I think it's much easier to code one REST API server and use it as a backend.
2) If I write my webapp authentication with oauth 2 standard is it a good way to store my secret token in cookie? I think this will cause CSRF vulnerability.
As i see passport.js uses cookies to store secret token for example for Facebook or twitter...
What's about CSRF in this case?
This is a very interesting question, I'm surprised nobody answered yet.
1) To the first question, my answer is definitely yes ! You don't want to write 2 times the API logic.
What you could do is to use different URLs.
Eg. For the public api, you use http://api.domain.com/objects/ whereas concerning the internal one, you could use http://domain.com/api/objects/ or whatever you prefer.
Then you use the same logic, but with different authentication strategies. Public one with authentication token, like many popular APIs (Twitter, Facebook etc.) and Private one using passport.js's logs.
The good thing about separating is :
You separate security issues
You can control access bandwidth if your app transfers a lot of data (and you want to give a higher priority to you app ... well probably !)
Or simply you can control authorizations (Eg. no DELETE through public API)
2) I'm not a security guru, but I would definitely trust passport.js authentication system, as it is widely used when using node as a backend.
You could refer to this question for implementing CSRF security in express : How to implement CSRF protection in Ajax calls using express.js (looking for complete example)?
Or another strategy is to use a refresh token if you use FB or Twitter connect strategies.
Hope it helps.

Securing a RESTful API

For my current side project, which is a modular web management system (which could contain modules for database management, cms, project management, resource management, time tracking, etc…), I want to expose the entire system as a RESTful API as I think that will make the system as more usable. The system itself is going to be coded in ASP.MET MVC3 however if I make all the data/actions available through a RESTful API, that should make the system very easy to use with PHP, Ruby, Python, etc… (they could even make there own interface to manage certain data if they wanted).
However, the one thing that seems hard to do easily (from the user's using the RESTful API point of view) with a RESTful API is security with ajax functionality. If I wanted something that was complex to setup and use, I would just create SOAP services but the whole drive for using a RESTful API is that it is very easy. The most common way of securing a RESTful API with with a key that is associated with a user. This works fine when all the calls are done on the server side however once you start doing ajax functionality, that changes. I would want the RESTful API to be able to be called directly from javascript however anyone who are firebug would easily be able to access the key the user is using allow that person access to the system. Is there a better way the secure a RESTful API where it does not make the user of the RESTful API do complex things just to set it up?
For one thing, you can't prevent the user of your API to not expose his key.
But, if you are writing a client for your API, I would suggest using your server side to do any requests to the API, while your HTML pages provide the data from the user. If you absolutely must use Javascript to make calls to the API and you still have a server side that populates the page in question, then you can obscure the actual key via a one-way digest algorithm in a timestamp-dependant way, while generating the page, and make it that your api checks that digest in a time-dependant way too.
Also, I'd suggest that you take a look into OAuth Nonces and timestamps a bit more deeply. Twitter and other API providers obviously have this problem too, so they must be doing something with the Nonce values.
It is possible to make some signature in request from javascript. But I'm hot sure, how 'RESTfull' urls would be with this extra info. And there you have the same problem: anyone who can see your making-signature-algorithm can make his own signature, witch you server will accept as well.
SSL stands for secure socket layer. It is crucial for security in REST API design. This will secure your API and make it less vulnerable to malicious attacks.
Other security measures you should take into consideration include: making the communication between server and client private and ensuring that anyone consuming the API doesn’t get more than what they request.
SSL certificates are not hard to load to a server and are available for free mostly during the first year. They are not expensive to buy in cases where they are not available for free.
The clear difference between the URL of a REST API that runs over SSL and the one which does not is the “s” in HTTP:
https :// mysite.com/posts runs on SSL.
http :// mysite.com/posts does not run on SSL.

Resources