React Login

Sample Project

Create an AuthService Class

The best way to have authentication utilities available across your application is to create a helper class. With the class in place, you can share an instance of it by passing it as a prop.

First, create an AuthService helper class to encapsulate the login functionality and save it inside the src/utils folder as AuthService.js.

Inside this class, create an Auth0Lock class that receives your Auth0 credentials and an options object. (For a list of available options, see: Lock: User configurable options). Instead of hard-coding your credentials in this class, they are passed from the AuthService constructor parameters to the Auth0Lock instance.

With the Auth0Lock instance, you can hook a callback for the authenticated event. This event will be triggered after every successful login, passing the user authentication token (idToken) as a parameter. The setToken method stores the idToken value in local storage.

Note: The client ID and domain for your application are passed to the AuthService in the above snippet, but the downloadable samples contain a .env.example file that should be renamed to .env and populated with these values.

In routes.js, there is now an onEnter callback assigned to the /home route. This calls requireAuth, which checks whether the user is authenticated, and redirects to /login if they are not.

Create the Login View

Create a new Login component and save it in src/views/Main/Login/. This React component should accept an auth object (which is an instance of the AuthServce) as a prop.

Persisting Application State

Lock uses redirect mode by default, meaning that a full page refresh will occur when users go through the authentication process in your application. This can be undesirable in single page apps, especially if the application contains state that should be displayed to the user again after they authenticate. For example, it may be the case that your users can initiate authentication from an arbitrary route within your single page app and you may want to return them to that location (along with any relevant state) after authentication is complete.

The recommended solution for this is to persist any necessary application state in local storage or a cookie before the user logs in or signs up. With this data, you can provide some custom post-authentication logic in the listener for the authenticated event to allow the user to pick up from where they left off.

In cases where storing application state is not possible, Lock's popup mode can be used. Please note that popup mode is not recommended. Known bugs in certain browsers prevent popup mode from functioning as expected under some circumstances.