Email-only authentication in Node.js - node.js

I am currently developing an application using a MERN stack, and I'd like to have authentication for it as well. However, before I just install PassportJS, I'd like to know how I should approach authentication. Should my client-side send my server a POST request with the email address in plaintext in the POST body? Should it encrypt it beforehand? Do I store the encrypted email address in MongoDB, or the plaintext version? I'm not asking for the best practice, but rather the approaches that could be taken given my current stack. I would like to understand this without just installing a package and calling the job done.

You have to use the middleware of passport inside your routes before calling your custom callback and defines passport with the great configuration

Related

Node.js express login cookie and URL

I am quite new to Node.js and I have two problems I cannot seem to be able to solve nor find any solutions on the internet.
If I want to create a login function (I have everything setup already except the cookies part) I have to somehow get the servers response, set a cookie and send it (express).
Now I'm wondering how should I get into this to use the variable in the login function?
The login function accepts callback, request, response as parameters. I wanted to return a callback whether the cookie is set after setting it. But the problem occurs when I want to set the cookie. I have to use response.send() which results in an infinite loop.
Is it possible to visit for example localhost/mywebsite and still get the server to work instead of
localhost:8080? (8080 is port I'm listening to, as an example)
This is a wonderful guide on setting up authentication in Express using a tried-and-true authentication library called Passport. And here is a second guide using an enterprise-grade (there's a free version) library from Auth0 and it has a lot more features regarding identity.
Update
So once the user logs in, you could send a cookie like this: res.cookie(cookieObject).send(responseObject) - more on this here. It would then be the browser/client-side framework's responsibility to return the cookie with every request. You could use the cookieparser package from NPM to help parse cookies from the req object. Let us know if this helps.

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

Best way to handle authentication on a react-redux single page appliction?

I'm currently sending the client an empty html document with a few scripts included that set up my single page application with react-redux. After everything is set up I'm fetching the dynamic data using AJAX and determine if the user is logged in or not. If the user is not logged in, he will see the products available only for users that are not authenticated and conversely.
Even though I am a noob, this seems extremly primitive to me and I don't know how I can do this better.
So what is the best way to handle authentication in react-redux applications?
Thanks a lot for helping.
There's a few options:
Passport which you can install through npm and it has a variety of strategies you can authenticate through such as Auth0 Link here
Firebase - a solution that google has that can be used as a drop-in authentication module. Link here
Meteor framework - I believe this framework has multi user authentication. Link here
First, for authentification you need to have a token or session id on the client side. So, there should be next steps:
After login, you receive token|session_id from backend and put it to the store and also to the localstorage not to lose it after page reload.
While initializing your app, get the token from localstorage and put it to the store every time.
When you do request for products list, add the token to ajax request (usually in headers).
Based on token, back-end application should returns another list of products.
It is a regular logic for such situations and of course it requires work on back-end side as well.

Nodejs user profiles and sessions

The goal is to build a user profile system for my web application. A user would be able to login, maintain a session and see his profile. After reading various tutorials online about how to do this, I feel a bit lost. Everyone uses different libraries and as someone new to web development, it's not clear what each library does. I've seen the following libraries used, can someone explain the flow of user-profile interactions and where each library comes in?
passport
passport-local
bcrypt-nodejs
connect-flash
express-session
jsonwebtoken
express-jwt
morgan
cookie-parser
One way to start your learning can be at:
https://www.youtube.com/watch?v=Z1ktxiqyiLA
There I learned how to use the most of plugins from your question.
Ok so about the plugins:
passport passport is a node.js plugin which is used usually with express that works as a middleware responsible for the authorization and authentication
passport-local - is a plugin for passport, more technically a strategy of authentication which usually is used with a database or configuration file.
bcrypt-nodejs is used usually for crypting the passwords in the database (but it is much more powerfull than that), is not cool to save password in plain text.
connect-flash - is used for flash messages that appears on a page "The user was successfully added", "Invalid user credentials", or any other success or error messages that you want to display on a page.
express-session - is an express middleware which is responsible to store the user session.
jsonwebtoken - jwt is used to create a token which you will use to identify if an user was authenticated or not.
express-jwt - an express middleware for jsonwebtoken
cookie-parser - an express middleware to parse cookies
morgan - just a log-ing service.
Ok so you should understand a bit of theory here:
passport with passport-local strategy is a statefull authentication mechanism which is supposed to save if the user is authenicated or not in a session, if you restart the node.js server if you did not persist your sessions in a third party service as a database/file etc... you will lose the sessions.
jsonwebtoken is a stateless authentication mechanism, you do not need to save anything on your server only the "secret key". Stateless architecture has some cool pros as it promotes horizontal scalability you can have endless nodes which will know how to parse the sended token and understand if the user is logged in or not. Lately I go with jwt as authentication.

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

Resources