Implementing user authentication can be a difficult task, because we can use various libraries and authentication strategies. There are a lot of tutorials on this topic, but often times they miss fundamental information or don’t reflect set up of our project. In this blog post, I don’t attempt to write an universal tutorial for user authentication. However, I will point out some parts in authentication flow I didn’t find in other tutorials.
We will be building a user authentication in a single page application with Node, React, Redux and Koa combined with Passport. I think this is a standard set up for Node.js projects, but what we will build is principally applicable to any SPA with unidirectional data flow. We will implement local authentication, where users can log in using an email and passport. We will also add authentication with Facebook, which can be used with other social networks and OAuth providers.
You can find a lot of good tutorials, which will help you implement user authentication in Node.js projects, but all these projects are multiple page applications:
- User Authentication with Passport and Koa
- Local Authentication Using Passport in Node.js
- Easy Node Authentication: Setup and Local
- Build User Authentication with Node.js, Express, Passport, and MongoDB
- Authenticating Users in a Node App using Express & Passport (Part One)
- Authenticating Node.js Applications With Passport
If you are looking for how to implement user authentication in React.js or Redux, you will probably come across these tutorial, which are very helpful:
- Secure Your React and Redux App with JWT Authentication
- Tips to handle Authentication in Redux #2 introducing redux-saga
- Protected routes and Authentication with React and Node.js
- storing user’s session information
- mocking a database with users
If you are looking for how to use PostgreSQL or MongoDB in Node.js, just check tutorials in the beginning of this article. For developing single page application, we will use React, React Router, Redux, Redux-Saga, Webpack and Twitter Bootstrap.
We will need to have Node, with npm, installed on our machine. We will also need to install Redis. Once all of the prerequisite software is set up, we can create the node application with the following command:
$ npm init
You’ll be prompted to put in basic information for Node project. We will need following dependencies.
For complete list, including development dependencies, check this file.
Now, install all the dependencies with command:
$ npm i
Below is an overview of project structure. Back-end is located in
├── script │ ├── controllers │ │ └── auth.js │ ├── views │ │ ├── about │ │ │ └── AboutView.js │ │ ├── actions │ │ │ ├── access.actions.js │ │ │ └── modals.actions.js │ │ ├── components │ │ │ ├── App │ │ │ ├── Header │ │ │ └── LoginForm │ │ ├── home │ │ │ └── HomeView.js │ │ ├── sagas │ │ │ ├── access.sagas.js │ │ │ ├── index.js │ │ │ └── modals.sagas.js │ │ ├── state │ │ │ ├── access.reducers.js │ │ │ ├── index.js │ │ │ └── modals.reducers.js │ │ └── routes.jsx │ └── server.js │ └── serverConfig.js ├── index.html ├── index.jsx ├── package.json └── webpack.config.js
Building and Setting up the Server
Now, when we install all npm packages, we can start to implement the server for our Node.js project. We create
server.js file in
Application Setup server.js
In the beginning of
server.js file, we just add required modules and create koa application.
If we open the terminal, we can run the application by command:
$ node ./script/server.js
"debug": "./node_modules/nodemon/bin/nodemon.js --inspect ./script/server.js"
Now we can initialize Redis and create a mock database with a user.
In the first line, we initialized Redis, then we created a new key
usersMockDatabase with a value – user object. We should always encrypt passwords before saving them to the database. In the code snippet above, I just pasted encrypted
test string using online bcrypt-calculator.
Next, we move session data out of memory into an external session store Redis.
We are setting up the router to specify how an application responds to a client requests to a particular endpoint. We will have the following routes.
Now we initialize passport along with its session authentication middleware. I highly recommend to check this article, which explains passport authentication flow.
In the first line, you can see, we required
./controllers/auth.js file, where is handled all the passport implementation. This is where we configure our authentication strategy for local and facebook. We will add required libraries, modules and implement serializing and de-serializing the user information to the session.
Passport Local Strategy
Next, we define passport’s strategy for handling login using a username and password. At first, we check the database for a user matching the given email. If a user with given email is found, the retrieved user’s password is compared to the one provided.
Passport Facebook Strategy
Before we implement facebook strategy, we need to create a new facebook aplication, set it up to enable OAuth and add redirect URIs. You can see more info here and here. Then we need to copy
serverConfig.js configuration files.
Adding Protected Endpoints
Passport also gives the ability to protect access to a specific route. It means that if user tries to access
http://localhost:1337/users/profile without authenticating, he will be redirected to home page by doing:
We should also implement Rate limiting to control how many requests a given consumer can send to the API. All successful API requests include the following three headers with details about the current rate limit status:
X-Rate-Limit-Limit – the number of requests allowed in a given time interval
X-Rate-Limit-Remaining – how many calls user has remaining in the same interval,
X-Rate-Limit-Reset – the time when the rate limit will be reset.
Most HTTP frameworks support it out of the box. For example, if you are using Koa and Redis, there is the koa-simple-ratelimit package.
Building and Setting up the SPA in React and Redux
Let’s start with implementing React entry point with views and other components.
Main React Entry File
At first we define
index.jsx, which bootstraps the react + redux application by rendering the
App component (wrapped in a redux Provider) into the
div element defined in the base
React + Redux App Component
App component is the root component for the React application, it contains routes, global alert notification and modal window for logging.
React + Redux Home Page and About Page
Now we will add home and about views. In home view we added
getProfile action, because we want see user profile data on this page.
React + Redux LoginForm Component
Next we can implement modal window, where users can log in.
LoginForm we implemented actions
loginUser used for logging user with email and password. Another action
toggleLogin is used for changing modal open state. Let’s say we want to display modal window for logging on other pages and in this case it is better to keep modal open state in a reducer instead of component’s state.
We don’t use an action for logging users with Facebook, you can see the explanation below. We need to save our current URL location in cookies, which we will need after Facebook successful login redirect.
Why is xhr getting blocked on the same url a browser can access?
Because it is a cross-domain request, and as such the remote party would have to allow that request first, which is what is referred to as CORS.
Facebook does not allow its login dialog to be loaded via script from different domains – for the obvious reason that users need to be able to be verify which site they are sending their login credentials to via the browser address bar, to avoid phishing.
You can not load the FB login dialog via XHR/AJAX in the background; you need to call/redirect to it in the top window instance.
Redux Actions Folder
Now we can implement actions.
Redux Sagas Folder
Next we will implement sagas.
We don’t want to lose user data, when we refresh a page after login. If we take a look at login saga worker, we can see that response data, which contains user object is stored in cookies. We can store user data somewhere else, but we shouldn’t do it in the reducer, because reducers should have no side effects. We need to get user data in a reducer, when we initialize state.
Ajax API Calls
Now we can implement API calls.
As you can see, we are using withCredentials property. If we use CORS and don’t set
true, isAuthenticated returns false and this passport’s method doesn’t work.
Redux Reducers Folder
Next, we can implement reducers.
React Router Routes
Now we can define routes.
After successful redirecting, we set a state
loadUser, which will be used in
componentWillReceiveProps method in
Header component to get user profile data.
If we want to make routes accessible only to authenticated users, we need to check documentation or tutorials on protected (authentication) routes for our routing library.
React + Redux Header Component
In this tutorial we implemented user authentication in a single page application using Node, Passport, React and Redux. The purpose of this article was to provide whole solution for authenticating with an email and password, and authenticating with an OAuth provider. We shouldn’t forget to implement rate limiting. If we host back-end and front-end on different servers, we need to use CORS and enable http headers for cross-site authentication. We can apply this tutorial in any SPA with unidirectional data flow. If you see any ways to improve this article, let me know please.