Auth0 — Embedded Login (ReactJS)

Tarun Singh
6 min readJan 19, 2021

Integrating Auth0 with ReactJS without using SDK and Universal Login.

Finally an article on what you have been looking for!

Introduction

I never had used Auth0 for authentication purposes, but recently I got to know that Auth0 is one of the best solutions out there. But there was this catch that it uses it’s own redirection flow in order to Login/Register a user. However the redirection flow is the most secure way of doing stuff with Auth0 (as they say this everywhere in their documentation) , there are obviously many use cases when you would need your own Login page, and would use there auth-functionalities. To be very honest, using the redirection flow would also hinder the user experience a bit.

The End Results can be found on my GitHub Repo. Do leave a ⭐.

CAUTION: This tutorial just covers the Auth0 Login + Register part and not on handling the auth context etc. This can be dealt later once the auth setup is done. However the GitHub Repo above is a full-fledged app with auth context, protected routes etc.

The Issue

So in the documentation of Auth0 the Embedded Login has not been given much importance and is poorly written for it.

If you are reading this for the first time without struggling beforehand as to how to NOT use the Universal flow, then you are lucky enough. Because I was not able to find any single source to demonstrate the implementation of Embedded Login with any tech-stack.

Thus, this article covers everything you would need to setup your embedded login in your app. Here I am using Auth0, however I am making simple Axios calls and thus this can even be implemented with any other frameworks as well.

Split-Up (Contents)

We would start with the boilerplate code of React using create-react-app. We would create some basic components link Home, Login, Profile etc. We would then create a service (Auth Service) which would handle all our auth requests.

So let’s begin!

Setup Auth0

Create an account on Auth0. Login and you will see a Dashboard. In the left menu tap on Applications. Now create a new application (tap on +Create Application Orange Button). Give a name and select Single Page Web Application. Now you will see your app listed beside the Generic App. Open your Application. In the settings tab you would see many credentials, we would require them later. But for now, scroll down and add http://localhost:3000 to Allowed Callback URLs, Allowed Logout URLs, Allowed Web Origins and Allowed Origins (CORS). Scroll more and tab Show Advanced Settings and check Password under Grant-Types.

Check the Password option under Grant-Types tab

Now from the left menu, tap on Connections. Here you will see a default database named “Username-Password-Authentication”. We will use it for storing user information.

Very Important Step: Now tap on your profile photo from top-left, select Settings. You will see the heading Tenant Settings. Under General tab scroll below to API-Authorization Settings and type the name of our DB exactly as it is under Default Directory.

Setup React

Create a new folder and using Terminal, browse into it. By the way do checkout the Windows Terminal, if using windows. Once inside the directory type: npx create-react-app .

Don’t forget the “dot” it would create the React App in the root level.

Create a .env file inside the root diretory and add the following to it:

REACT_APP_CLIENT_ID = YOUR_CLIENT_ID

REACT_APP_DOMAIN = https://YOUR_AUTH0_USERNAME.us.auth0.com, // For Example https://tarunsingh.us.auth0.com

REACT_APP_CONNECTION = Username-Password-Authentication

The Client ID would be found under the settings tab of our application that we created on Auth0.

We created these environment variables and would use them in our app. For that we use the “dotenv” package to read the environment vars.

Now do the following inside src:

Create a components folder. Within it create folders namely Home, Login, Register, Profile, Navbar. Each of these would have a .js .module.css and .test.js (optional) files.

Components Structure

Next, create a services folder and inside it create a file AuthService.js. This is the file that will handle all our auth requests. Let’s now work on this file as this the crux of the whole flow.

We would create 4 functions here which would be deal with the auth part.

Explanation of the 4 Auth Functions:

register(email, password): This function would be called when you hit the register button on the register page. We have to append a config object with our axios request. Let’s create it. The user’s email and password would be passed as args. Now we need to encapsulate them within the data packet. We create the data object with client_id and connection being used from the Environment variables. Note: Connection string is the name of the Database. We then create a config object with method post, the url is the DOMAIN + “/dbconnections/signup”. Headers should be of “Content-Type”: “application/x-www-form-urlencoded”. We then make the axios request and handle it with appropriate messages.

Now you can cross-check that the user object has been created. Go to Auth0 Dashboard and now tap on the left-menu Users & Roles -> Users. You will see your newly registered user.

User has now successfully registered.

login(username, password): With this function we create a similar axios request. Here in the data object we are supposed to pass the username key with value as the email as we didn’t setup a username while registering. We can add the scope as “openid” or “profile”. This request would hit “/oauth/token” endpoint off the Auth0 api. On a successful authorized request we get an access_token as a response. This token defines the user is authorized. We save it to the browser’s local storage and would use it later to make any requests to our protected resource (such as the user profile).

User has now successfully logged in.

getUserProfile(): This function makes a axios request to “/userinfo” endpoint, sending the access token in Authorization header (Bearer token). We get a response which is an object with all the user details. We use this function to populate the user profile fields.

User profile is now fetched successfully.

isAuthenticated(): This function checks the validity of our access_token. We decode the token (using jwt-decode) which spills out the expiration date of the token. Comparing this date with the current date we return true or false. We can use this function to protect the routes in our app.

Connecting the Strings

Since we have completed the auth services part, we can now easily connect it with the Login, Register and Profile components. You may refer to the code (Github) as to how I did that.

Wrap Up

Once done you can modify this app to suit your use case. You can read more about Auth0 API and ca work with refresh tokens etc.

Personal Advice: It’s better to make axios calls to the API rather than using the auth0-js library which has some incomplete documentation.

Thanks for reading! Share it as this content is not yet seen anywhere (as far as my research goes).

--

--