Created with Sketch.
SING UP

TL;DR: You can check out a React Flux app with authentication implemented in this Github repository


Let’s face it. React is the new cool kid on the block. Everybody is working on creating React components because it entails understanding just 2 basic concepts:

  • A component is just a function
  • Single-direction data flow

However, once you start creating a bigger app, you realize that just using React isn’t enough. So you start looking at Flux, which is the architecture Facebook uses to create React apps.

As we learned in a previous blog post, learning how to conduct authentication in a Single Page App can get super complex. We had to learn about tokens, JWTs and how to integrate them with SPAs. Learning how to do it with Flux is even harder! That’s why in this blogpost we’ll learn how to add authentication to a React Flux app.

"Learning how to conduct authentication in a Single Page App can get super complex"

Before we start

We’ll be coding our React app using ES6 thanks to Browserify and Babelify, and we’ll be using npm for build tools and installing dependencies. If you want to start a project with the same architecture, just clone this seed project.

Coding ReactJS Authentication!

Login page

The Login component

First, let’s create our Login component. Its main function is rendering an input for the username and password and calling the AuthService when the user clicks on the login button.

// ... imports
export default class Login extends React.Component {

  constructor() {
    this.state = {
      user: ‘’,
      password: ‘’
    };
  }

  // This will be called when the user clicks on the login button
  login(e) {
    e.preventDefault();
    // Here, we call an external AuthService. We’ll create it in the next step
    Auth.login(this.state.user, this.state.password)
      .catch(function(err) {
        console.log(“Error logging in”, err);
      });
  }

  render() {
    return (
        <form role=“form”>
        <div className=“form-group”>
          <input type=“text” valueLink={this.linkState(‘user’)}placeholder=“Username” />
          <input type=“password” valueLink={this.linkState(‘password’)} placeholder=“Password” />
        </div>
        <button type=“submit” onClick={this.login.bind(this)}>Submit</button>
      </form>
    </div>
    );
  }
}

// We’re using the mixin `LinkStateMixin` to have two-way databinding between our component and the HTML.
reactMixin(Login.prototype, React.addons.LinkedStateMixin);

The AuthService & the LoginAction

Our AuthService is in charge of calling our login API. The server will validate the username and password and return a token (JWT) back to our app. Once we get it, we’ll create a LoginAction and send it to all the Stores using the Dispatcher from Flux.

// AuthService.js
// ... imports
class AuthService {

  login(username, password) {
    // We call the server to log the user in.
    return when(request({
      url: ‘http://localhost:3001/sessions/create',
      method: ‘POST’,
      crossOrigin: true,
      type: ‘json’,
      data: {
        username, password
      }
    }))
    .then(function(response) {
        // We get a JWT back.
        let jwt = response.id_token;
        // We trigger the LoginAction with that JWT.
        LoginActions.loginUser(jwt);
        return true;
    });
  }
}

export default new AuthService()
// LoginAction.js
// ... imports
export default {
  loginUser: (jwt) => {
    // Go to the Home page once the user is logged in
    RouterContainer.get().transitionTo(‘/‘);
    // We save the JWT in localStorage to keep the user authenticated. We’ll learn more about this later.
    localStorage.setItem(‘jwt’, jwt);
    // Send the action to all stores through the Dispatcher
    AppDispatcher.dispatch({
      actionType: LOGIN_USER,
      jwt: jwt
    });
  }
}

You can take a look at the router configuration on Github, but it’s important to note that once the LoginAction is triggered, the user is successfully authenticated. Therefore, we need to redirect him or her from the Login page to the Home. That’s why we’re adding the URL transition in here.

The LoginStore

The LoginStore, like any other store, has 2 functions:

  • It holds the data it gets from the actions. In our case, that data will be used by all components that need to display the user information.
  • It inherits from EventEmmiter. It’ll emit a change event every time its data changes so that Components can be rendered again.
// ... imports
class LoginStore extends BaseStore {

  constructor() {
    // First we register to the Dispatcher to listen for actions.
    this.dispatchToken = AppDispatcher.register(this._registerToActions.bind(this));
    this._user = null;
    this._jwt = null;
  }

  _registerToActions(action) {
    switch(action.actionType) {
      case USER_LOGGED_IN:
        // We get the JWT from the action and save it locally.
        this._jwt = action.jwt;
        // Then we decode it to get the user information.
        this._user = jwt_decode(this._jwt);
        // And we emit a change to all components that are listening.
        // This method is implemented in the `BaseStore`.
        this.emitChange();
        break;
      default:
        break;
    };
  }

  // Just getters for the properties it got from the action.
  get user() {
    return this._user;
  }

  get jwt() {
    return this._jwt;
  }

  isLoggedIn() {
    return !!this._user;
  }
}
export default new LoginStore();

You can take a look at the BaseStore in Github. It includes some utility methods that all stores will have.

Displaying the user information

Creating an Authenticated component

Now, we can start creating components that require authentication. For that, we’ll create a wrapper (or decorator) component called AuthenticatedComponent. It’ll make sure the user is authenticated before displaying its content. If the user isn’t authenticated, it’ll redirect him or her to the Login page. Otherwise, it’ll send the user information to the component it’s wrapping:

// ... imports
export default (ComposedComponent) => {
  return class AuthenticatedComponent extends React.Component {

    static willTransitionTo(transition) {
      // This method is called before transitioning to this component. If the user is not logged in, we’ll send him or her to the Login page.
      if (!LoginStore.isLoggedIn()) {
        transition.redirect(‘/login’);
      }
    }

    constructor() {
      this.state = this._getLoginState();
    }

    _getLoginState() {
      return {
        userLoggedIn: LoginStore.isLoggedIn(),
        user: LoginStore.user,
        jwt: LoginStore.jwt
      };
    }

    // Here, we’re subscribing to changes in the LoginStore we created before. Remember that the LoginStore is an EventEmmiter.
    componentDidMount() {
      LoginStore.addChangeListener(this._onChange.bind(this));
    }

    // After any change, we update the component’s state so that it’s rendered again.
    _onChange() {
      this.setState(this._getLoginState());
    }

    componentWillUnmount() {
        LoginStore.removeChangeListener(this._onChange.bind(this));
    }

    render() {
      return (
      <ComposedComponent
        {...this.props}
        user={this.state.user}
        jwt={this.state.jwt}
        userLoggedIn={this.state.userLoggedIn} />
      );
    }
  }
};

An interesting pattern is used here. First, take a look at what we’re exporting. We’re exporting a function that receives a Component as a parameter and then returns a new Component that wraps the one that was sent as an argument. Next, take a look at the render method. There, we’re rendering the Component we received as a parameter. Besides the props it should receive, we’re also sending it all the user information so it can use those properties. Now, let’s create the Home component which will be wrapped by the AuthenticatedComponent we’ve just created.

Home Page

The Home will display user information. As it’s wrapped by the AuthenticatedComponent, we can be sure of 2 things:

  • Once the render method is called on the Home component, we know the user is authenticated. Otherwise, the app would have redirected him to the Login page.
  • We know we’ll have the user information under props because we’ve received them from the AuthenticatedComponent
// ... imports
// We’re wrapping the home with the AuthenticatedComponent
export default AuthenticatedComponent(class Home extends React.Component {
  render() {
     // Here, we display the user information
    return (<h1>Hello {this.props.user.username}</h1>);
  }
});

Let’s call an API!

Now, you should be able to call an API. In order to call an API that requires authentication, you must send the JWT we received on Login in the Authorization header. Any AuthenticatedComponent has access to this JWT so you can do something as follows:

// Home.jsx
// It must be on an AuthenticatedComponent
callApi() {
  fetch(‘http://example.com/my-cool-url', {
    method: ‘GET’,
    headers: {
      Authorization: ‘Bearer ‘ + this.props.jwt
    }
  }

Keeping the user authenticated

Now that the user is authenticated, we want to keep him or her authenticated instead of showing the login page every time he refreshes the website. Due to the fact we’re saving the JWT on localStorage after a successful authentication, we can manually trigger the LoginAction and everything will work. That’s the beauty of using Flux.

// app.jsx ==> Bootstrap file
let jwt = localStorage.getItem(‘jwt’);
if (jwt) {
  LoginActions.loginUser(jwt);
}

Aside: Authenticate a React App with Auth0

We can protect our applications and APIs so that only authenticated users can access them. Let's explore how to do this with a React application using Auth0.

Auth0 login screen

We'll need an Auth0 account to manage authentication. To sign up for a free account, we can follow this link. Next, let's set up an Auth0 client app and API so Auth0 can interface with a React App.

Setting Up a Client App

  1. Let's go to our Auth0 Dashboard and click the "create a new client" button.
  2. Let's call our app as "React Demo" and select "Single Page Web Applications".
  3. In the Settings for our new Auth0 client app, let's add http://localhost:3000/callback to the Allowed Callback URLs.
  4. If desired, we can set up some social connections. We can then enable them for our app in the Client options under the Connections tab. The example shown in the screenshot above utilizes username/password database, Facebook, Google, and Twitter. For production, make sure to set up the correct social keys and do not leave social connections set to use Auth0 dev keys.

Set Up an API

  1. Go to APIs in your Auth0 dashboard and click on the "Create API" button. Enter a name for the API. Set the Identifier to your API endpoint URL. In this example, this is http://localhost:3001/api/. The Signing Algorithm should be RS256.
  2. You can consult the Node.js example under the Quick Start tab in your new API's settings. We'll implement our Node API in this fashion, using Express, express-jwt, and jwks-rsa.

We're now ready to implement Auth0 authentication on both our React client and Node backend API.

Dependencies and Setup

There are only two dependencies that we really need to install: auth0.js and history. To do that, let's issue npm install --save auth0-js history in the project root.

Note: As we want the best security available, we are going to rely on the Auth0 login page. This method consists of redirecting users to a login page hosted by Auth0 that is easily customizable right from the Dashboard.

After installing it, we can create an authentication service to interface with the auth0.js script. Let's call this service Auth and create it in the src/Auth/ directory with the following code:

import history from '../history';
import auth0 from 'auth0-js';

export default class Auth {
  auth0 = new auth0.WebAuth({
    // the following three lines MUST be updated
    domain: 'bkrebs.auth0.com',
    audience: 'https://bkrebs.auth0.com/userinfo',
    clientID: '3co4Cdt3h3x8En7Cj0s7Zg5FxhKOjeeK',
    redirectUri: 'http://localhost:3000/callback',
    responseType: 'token',
    scope: 'openid'
  });

  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
  }

  handleAuthentication() {
    this.auth0.parseHash((err, authResult) => {
      if (authResult && authResult.accessToken) {
        this.setSession(authResult);
        history.replace('/home');
      } else if (err) {
        history.replace('/home');
        console.log(err);
      }
    });
  }

  setSession(authResult) {
    // Set the time that the access token will expire at
    let expiresAt = JSON.stringify((authResult.expiresIn * 1000) + new Date().getTime());
    localStorage.setItem('access_token', authResult.accessToken);
    localStorage.setItem('expires_at', expiresAt);
    // navigate to the home route
    history.replace('/home');
  }

  login() {
    this.auth0.authorize();
  }

  logout() {
    // Clear access token and expiration from local storage
    localStorage.removeItem('access_token');
    localStorage.removeItem('expires_at');
    // navigate to the home route
    history.replace('/home');
  }

  isAuthenticated() {
    // Check whether the current time is past the
    // access token's expiry time
    let expiresAt = JSON.parse(localStorage.getItem('expires_at'));
    return new Date().getTime() < expiresAt;
  }
}

The Auth service just created contains functions to deal with various steps of the sign in/sign up process. The following list briefly summarizes these functions and their descriptions:

  • handleAuthentication: looks for the result of the authentication in the URL hash. Then, process the result with the parseHash method from auth0-js;
  • setSession: sets the user's access token and the access token's expiry time;
  • login: initiates the login process, redirecting users to the login page;
  • logout: removes the user's tokens and expiry time from browser storage;
  • isAuthenticated: checks whether the expiry time for the user's access token has passed;

Besides these functions, the class contains a field called auth0 that is initialized with values extracted from the Auth0 client. Let's keep in mind that we need to update them accordingly before proceeding.

Attentive readers probably noticed that the Auth service also imports a module called history that we haven't talked about. We can define this module in only two lines, but let's define it in a file to provide reusability. Let's call this file ./src/history/history.js and add the following code:

import createHistory from 'history/createBrowserHistory'

export default createHistory()

After creating both elements, we can refactor our App component to make use of the Auth service.

import React, { Component } from 'react';
import { Navbar, Button } from 'react-bootstrap';
import './App.css';

class App extends Component {
  goTo(route) {
    this.props.history.replace(`/${route}`)
  }

  login() {
    this.props.auth.login();
  }

  logout() {
    this.props.auth.logout();
  }

  render() {
    const { isAuthenticated } = this.props.auth;

    // ... render the view
  }
}

export default App;

Note that we are passing this service through props. Therefore, when including the App component, we need to inject Auth into it: <App auth={auth} />.

Considering that we are using the Auth0 login page, our users are taken away from the application. However, after they authenticate, users automatically return to the callback URL that we set up previously (http://localhost:3000/callback). This means that we need to create a component responsible for this URL:

import React, { Component } from 'react';
import loading from './loading.svg';

class Callback extends Component {
  render() {
    const style = //...

    return (
      <div style={style}>
        <img src={loading} alt="loading"/>
      </div>
    );
  }
}

export default Callback;

This component can just contain a loading indicator that keeps spinning while the application sets up a client-side session for the users. After the session is set up, we can redirect users to another route.

Please refer to the official Quick Start Guide to see, step by step, how to properly secure a React application. Besides the steps shown in this section, the guide also shows:

Closing remarks

We’ve finished implementing the Login for a React Flux app. If you want to know how to implement a signup or if you want to see the full example at work, you can grab the code from Github.

Happy Hacking! :).