Authentication middleware in Express NodeJS - Best practice - node.js

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 :)

Related

Question regarding passport.js' level of security

Just have some general questions about the level of security one can expect when using passport for an App's Authentication;
I am currently in the process of designing my first App using a MongoDB, Express, React and Node.js stack. Without having much prior knowledge about cyber security I have done quite a bit of research about authentication and what type of attacks can occur on my site. I have opted to use a cookie-based authentication system with the passport.js npm package and I have designed my /login route to require that the user's password and username first pass a passport.authenticate('local', ....) middleware setup before a session and cookie are created.
In order to persist the current user in my react app, I have a function which requests the server to provide it with the currently active passport session if there is one - and this seems to work as it will not maintain a login state if the user deletes the session cookie from their browser.
I am a bit skeptical of passport and I'm curious to know how easily it could be breached by someone who has a higher understanding of how it works, so the things I am wondering are several:
Is this type of authentication setup secure?
Are there any additional requirements that one must implement in order for passport to be a
legitimate method of authentication for an App?
Is using passport to authenticate users considered to be bad practice? Would showcasing an app that
authenticates users by using an npm package look bad if I were to showcase this application to a
potential employer?
I can share code if necessary to better illustrate my code setup, although I would prefer not to if at all possible. Any advice would be much appreciated, thanks!
TLDR:
Is passport.js a secure method to authenticate users? Is using passport.js for this bad practice?
Passport.js provides authentication, not security. It is fairly easy to misconfigure by following online tutorials, so take care - the tool is only as good as the hand it is in. To add security to passport, you will need at the very least three additional elements:
Strong state model for the session (or token) that does not leak private fields and uses argon2 for password hashing.
No mistakes on the front-end with CSRF or XSS.
Rate and buffer limitters on Node itself or, even better, on your reverse proxy.

Security for React front-end and Node back-end

I'm relatively new to the modern JavaScript web development world. I've built a very simple Node/Express back-end and a separate React front-end. My vague plan is to have users that will have permission to access certain areas of the front-end, and then have the front-end make requests to the back-end. Can the front-end and back-end share the same authentication/authorization scheme? Can they both use something like Auth0? How can I make these two secure?
I'm a little stuck and would appreciate any advice or a nudge in the right direction. I'm mostly stuck because these are two separate applications but the same "user" would technically have permissions to certain React views as well as certain Express endpoints - how they moosh together?
Thanks.
Although seems not directly related to your topic, but I would actually suggest you try Meteor if you are not planning to immediately start working on large projects (not pressing too hard on scalability).
Meteor has a builtin support for Accounts and interacts with MongoDB nicely, and it also has its own DDP protocol that simplifies API call massively. It also interacts nicely with React.
If you think Meteor might not be a good choice for yourself, you could still learn from its design policies of authorization, etc. It has quite a bit package source code that are not too difficult to understand, and should be helpful for you to learn the basic idea. (Actually, Meteor's Accounts package already implements the basic idea mentioned by another answerer, you can learn from its design principles)
When users log in to your site, issue them with an access token that they keep client side. On front-end, check if user has token and correct permissions before rendering components. On back-end, send the token as request headers to the endpoints.
I have implemented a similar case, but with the spring boot kotlin at the backend instead. My solution is using JWT token to validate the authentication and authorization.
User logins by input login form and send POST method to backend via a REST API.Backend validates credential and returns the JWT token including encrypted user_role, expiration date, etc... if valid or 403 exception
Front-end decodes the JWT (using jwt-decode lib or something else),
save it to validate the access permission to specific page in the
website based on user_role. Eg: role='ADMIN' can access to admin dashboard page, role='USER' can access user profile page, etc.
If you use express as the backend, I suggest to use the feathersjs. It has backend solutions for this and an optional front end version. Refer: https://docs.feathersjs.com/api/authentication/jwt.html
Secure Front end (React.js) and Back end (Node.js/Express Rest API) with Keycloak follow this

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!

Authorisation strategy for a first-party express based node API

I'm tackling the design of my first API and am struggling somewhat with authorisation concepts - I was hoping some kind people could give me some advice!
What I'm building:
An API that will eventually be accessed by third party apps and a mobile app.
A web-based 'client' (first-party single page app) that will use the API. (Should this first-party app be 'a part' of the API, or a completely separate node app?)
Technology I plan to use:
Node
Express
Passport
Mongodb with Mongoose
I'm not wed to express or passport, they just seem like the best options and are well documented - bit I wouldn't want a potential solution to be dismissed because of alternative dependencies. Same with Mongoose, I actually prefer the look of Monk (or even just Mongojs), but every tut seems to use mongoose, so seems like the safest option for a node beginner.
Authenticating a user is simple enough (I've gone through the fantastic Beer Locker tutorial), what I'm struggling with is ongoing authorisation. Naturally I don't want the user to have to input a username and password with every request they make - should this information be stored locally and sent with every request? (if so, how? I can't find any info on handling an API with a session) or should I be working with tokens of some sort? The small amount of reading I did on 'Digest' authorisation (including the Beer Locker tutorial follow-up) made it seem like it had security issues, at least with the Passport implementation (this I don't fully understand, but seems to relate to hashing passwords, which passport doesn't do as standard, and only MD5 is supported even if it's added?).
I have built a working API that I can authorise with 'Basic' (directly, through Postman), so I have the foundations in place - authorisation works, I just need the tools to take that to the next step and add sessions into the mix!
I've been trying to get my head around this for a couple of days now, but I fear I'm too stuck in a more traditional local web-app workflow - the whole API thing is throwing me somewhat.
Any help is hugely appreciated, even if it's just pointing me at an appropriate tutorial - the above set of requirements must be quite common!
I have come accross this problem too...
I can only recommend doing this for the beginning:
http://scotch.io/tutorials/javascript/easy-node-authentication-setup-and-local
tell me if it helped :)
As I understand you have done the authentication and the only thing you have to do now is store somewhere that the current user is authenticated, his name, roles etc to use later with other requests. In the Passport you will do it in the function callback (instead of the "If this function gets called..." comment).
Now you have to decide, you have two options:
Store the user information (name, roles etc.) on your server (in a session) and give the user some long code which will identify his session for the next requests
to store the information on your server you may use for example the express-session middleware
it would be probably best to save the session identifier in a cookie, but read some security issues before
Give the user something that would prove to you he/she is authenticated and which name, roles etc. he/she has
you can generate a token, that contains the user information (name, roles etc.) that the user will send with every request. to know this token is legit, you will have to sign it. more on this is on jwt.io and you can use express-jwt middleware.
you dont have to care about storage of session with this one
the token can be placed to a cookie too, but same security issues apply. it is still considered better that localstorage (more here)

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.

Resources