Authenticating Users in SPA using Node, Passport, React and Redux

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:

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.

Getting Started

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.

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.

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 clientID, clientSecret and callbackURL into .env and 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:

Rate Limiting

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 intervalX-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.

CORS

When we develop single page applications, we usually deploy front-end code on different server than API. In this case, we need to allow CORS and enable Access-Control-Allow-Credentials.

Building and Setting up the SPA in React and Redux

Back-end part in Node.js is ready and now we can implement SPA in React and Redux. We will focus on unidirectional data flow in single page applications. The same principles can be applied to other frameworks or libraries for implementing unidirectional data flow such as Flux or MobX. In this project I decided to use popular libraries React, React-Router, Redux and Redux-Saga. Redux is a state container for JavaScript applicatins that describes the state of the application as a single object and Redux-Saga is used to make handling side effects in Redux nice and simple.

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 index.html.

React + Redux App Component

The 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.

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 withCredentials to true, isAuthenticated returns false and this passport’s method doesn’t work.

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

Conclusion

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.