Authenticating React Apps Using Auth0
In this talk, I'll be giving you an introduction to the different authentication strategies and then I'll be showing you how to add authentication to a React app using Auth0
Transcript
Muhammad Abdelwahab: [0:00] Hi, I'm Muhammad Abdelwahab, [laughs] also known as Mahmoud. I'm a front end developer, and instructor at egghead, and an ambassador for AUTH0. In today's talk, I'll be giving you an introduction to what is authentication, the different authentication strategies.
[0:16] In the end, I'll be adding authentication to a React app, using AUTH0, which is an authentication service provider. Before getting started, I want to say huge thanks to egghead for organizing this awesome event. Now, let's get started.
[0:30] If you were to build an app today, it doesn't matter which industry, which category, there's a high chance that you're going to need this one feature, and it's authentication. What is authentication any way?
[0:43] You may have seen the recent Twitter attack, where accounts of famous people like Bill Gates, Jeff Bezos, Kanye West, were hacked, and a Tweet was posted saying, "Donate money to this Bitcoin wallet and you'll be given twice the amount." Of course this was a scam, but eventually it got taken down and things were fixed.
[1:04] Here's an important question. How can an app know that the user is who they say they are? For example, for me to upload a video to YouTube, I need to be logged in. How can YouTube tell that it's me?
[1:18] There are many strategies. The first one being email and password. Of course, YouTube wants to keep my account safe. When using email and password, it will add password requirements to make my password hard to guess.
[1:29] Another strategy is to use passwordless authentication. If you've used Slack, for example, or Notion, you enter your email, you are then sent a unique link, and when you use this link you're in. There's using social login, where you let a social network provider, like Google, Facebook, Twitter, GitHub, and many more to take care of the authentication process for you.
[1:51] There's also multi factor authentication, where users need to provide more than one piece of identifying information. Not just a password, but a password plus a verification code sent to the user's email or phone.
[2:05] There's single sign on, where you are automatically logged in, in different places when you login in one place. Think Google products, you log into Gmail and then you logged in inside calendar, notes, and YouTube. You can also use a biometric device like a fingerprint scanner or using facial recognition. Of course, all these strategies are not perfect. Each one has its own pros and cons.
[2:27] For example, if you decide to build email plus password authentication, well, you have to build a different flows. For example, you need to implement change password, forgot password, verification email. Also, you are responsible for the users' data. You have to keep it safe and secure.
[2:48] On the other hand, if you pick login with Google or login with Facebook or login with GitHub, not everyone wants to use that. Some users prefer using classic email and password. This way, you may be sacrificing potential users, or maybe you go for multifactor authentication.
[3:06] Now while it is more secure, it can be more expensive, because you will need to send out SMS verification codes to users and this costs money. As you can see, it's not simple to add this necessary feature. Unfortunately, it doesn't make you money. It doesn't make you stand out in any way. In fact, it's expected.
[3:29] You see, managing users and authentication is complex to the point where there are businesses built on the idea of managing authentication for you. You have Auth0, you have Okta, you have Firebase Authentication, you have AWS Cognito, and they all do the same thing. They manage user authentication for you. They make it easy for you to add this feature. Of course, they cost money.
[3:58] Now there's an important question -- should you build or should you buy? Now you may be thinking, "Hey, I'm a developer. Why don't I build my own authentication solution from scratch? I don't need to pay any money. I'll spend some time upfront building this feature and keep using it."
[4:17] While that is true, you will still need to maintain this code and make sure that it's safe and secure. For example, Google login may have a breaking change, and you need to integrate that in your own authentication solution. Plus, it's a huge responsibility to protect users' data.
[4:38] That's why giving this responsibility to a SaaS might be a good solution. Plus, you don't do a lot of effort to build this feature. You can focus on building business logic or the features that can actually make you stand out.
[4:57] In conclusion, it's all about three things -- time, money, and effort, which matters to you the most. If you care about saving money, then build your own authentication system and make sure that it's secure. You will need to spend time and effort.
[5:12] On the other hand, if you care about saving time and effort, then you're going to have to spend some money. Right now, I will show you how easy it is to use an authentication service provider. I'll be using Auth0 to secure a React app.
[5:27] This is the end result of what we will be building today. This is a landing page for a fictional startup. It's just a Counting app. It's still in early access, and you have the elements of any landing page.
[5:44] You have the features. We can increment the counter, decrement it, and also auto-saves your progress, but it technically doesn't because it uses localStorage. There is no payments yet. We will just be adding the authentication.
[6:02] You have the Customer Reviews section. These are fake reviews. No one has used the app yet. Finally, you have the Frequently Asked Questions section. This page is accessible by anyone. You don't need to be authenticated, and you can either sign up or log in. I already have an account, so I'll just log in. I'll continue with Google.
[6:30] You have the Login view. This is pulling my name from Auth0 and also my picture. You have the Logout button and this counter increments, decrements. If you refresh the page, it's still there. Finally, we can log out and we redirected to the landing page, so let's see how we can build this.
[6:57] The first thing that you'll need is go to auth0.com and make sure that you have an account. The Sign Up process is pretty simple. You'll pick a region, and you'll pick whether the account is Personal or for a Company, then click Create account.
[7:14] After the account is created, you will have this page. This is the Login view for Auth0. What you need to do is go to the sidebar, to the left, to the Applications, click on that. What you need to do is create an application.
[7:32] Since this is a React app, we're going to pick Single Page Web app. You can name this app whatever you want. I'll just name it Demo, and then I'll click Create.
[7:46] After it's done creating the app, what you need to do is go to the Settings tab. Here, you'll configure Auth0, and you will find information about to Auth0 app. The first one being the Domain, the Client ID. There's also the Client Secret. Before using the Client ID and the Domain, what we need to do is configure the Application URIs.
[8:09] The first one being the Allowed Callback URLs. A callback URL is a URL in your application, where Auth0 redirects the user after they have authenticated. What we need to do, we'll do the same for the Logout URL and the Allowed Web Origins.
[8:28] As you can see, I'm putting in http://localhost:3000, because this is my development environment. Usually, what you'll do when the app is deployed, you will put the URL of the live app. The Logout URL is a URL in your application that Auth0 can return to after the user has been logged out. This usually is the landing page.
[8:55] Finally, you have the Allowed Web Origins, which will refresh the authentication tokens, and your users will not be logged out the next time they visit the application or refresh the page. After that's done, just go to the bottom and click Save.
[9:13] We're inside our React app. I already created a .env file. Inside of it, you'll find two variables -- one for the Auth0 Domain and the other for the Client ID. We'll get to these two values from the Settings and we'll just copy and paste them. That's it. These are the only two things that we'll need.
[9:38] The next thing that we need to do is install Auth0 React SDK. We do that by running $ yarn add @auth0/auth0-react. If you're using npm, just run npm install instead.
[9:52] [pause]
Muhammad: [10:07] We're inside our index.js file, and what we'll need to do is wrap our entire app and an Auth0Provider since it uses React context under the hood.
[10:19] Why do we even need that, Moud? Because the authentication process doesn't happen within the Application layer. React will redirect users to Auth0'z Login page, where Auth0 will simply ask for credentials and then redirects the user back to the application.
[10:37] The Auth0Provider remembers where the users wanted to go if authentication were successful or not, and it takes users to that route. This way, since we need to know information about the user's navigation, we need to access the session history of the application.
[10:58] Since we're using React router to manage the routing for this React app, React router exposes a React hook that makes it very easy for us to access the session history. The hook is called the useHistory, and it gives us a history object.
[11:15] The first thing that we need to do is import {useHistory} from "react-router-dom". We'll import {Auth0Provider} from "@auth0/auth0-react" and we're going to create the Auth0ProviderWithHistory component. It takes as a prop children. What we need to do right now is called the useHistory(), and we'll also import the domain and the clientId from our environment variables.
[11:43] We're going to write a function called onRedirectCallback. This function handles the event where Auth0 redirects users from Auth0's Login page to the React app. We use the useHistory() to get the history object from React router and use history.push to take users back to the route that they intended to access before authenticating.
[12:09] What we'll need to do is return the Auth0Provider and also add the children. What we'll need to do is just pass the domain to the domain prop and the client ID the clientId prop. For the redirectUri, we will pass window.location.origin and then for the onRedirectCallback, we'll just pass our onRedirectCallback function.
[12:33] We're back our index.js file. All we need to do is just wrap the App component with our Auth0ProviderWithHistory. We also need to make sure that the Auth0ProviderWithHistory is wrapped with our router.
[12:48] Right now, what we want to do is make our Login and Sign up buttons functional. Once the user is logged in, we want to display the user's picture and a Logout button.
[12:58] As you can see, we're inside the Navbar component. These are two buttons -- a Sign up button and a Login button. To get started, the first thing that we need to do is import the {useAuth0} from "@auth0/auth0-react". What we need to do is get a couple of values from this hook.
[13:18] The first one being loginWithRedirect, which is a function that allows users to log in. We also get logout, which is the function that allows users to log out, isAuthenticated, which will tell us whether the user is authenticated or not, and then finally, the user object.
[13:35] The user object contains data about the logged in user. For example, the name, the email, the picture, and we're getting the picture from this user object by destructuring it.
[13:46] I added the markup for the Logout button and the image, and I'm just passing the picture as the source. All we need to do is use the isAuthenticated variable and using conditional rendering, we will either display the Sign up on Login button if the user is not authenticated. Else, we'll just display the Logout button and the user's picture.
[14:11] What we'll need to do is add an onClick event handler, which we'll just call the loginWithRedirect. The loginWithRedirect takes as a parameter and object. This object contains the screen_hint, which is signup.
[14:24] This is when using Auth0's new universal Login, which allows you to customize Auth0's Login page. For the Login button, we'll also add an onClick and just call loginWithRedirect. Finally, for the Logout button, we'll also add an onClick handler and just call the logout function and pass to an object with a key returnTo and the value of windows.location.origin.
[14:49] We're inside the app.js file, which holds the routes of our app. What I want to do is check if the user is authenticated or not. If the user is not authenticated, load the Landing page. If they're authenticated, load the Login view, which here, it's called the Home.
[15:08] All I need to do is just pull {useAuth0} again. I have a loading component that I wrote, and what I'm going to do is pull {isLoading, isAuthenticated} from the useAuth0(). I will check if isLoading, which means that we're in the process of authenticating, and if that's true, we'll display the Loading component.
[15:36] Using conditional rendering, all we need to do is just check if the user is not authenticated, and then we'll display the Landing page. Else, we'll just the Home page component.
[15:52] That's it. We can sign up. We can login. I already have an account, so I'll just log in with Google. You pick any account. You saw the Loading component, and you're seeing my name. I'm pulling this again the same way that I did from the user object, from Auth0. As you can see, we also have the picture and the Logout button.
[16:19] If you're interested in the code, it is public on GitHub, so feel free to clone it. Play around with it. Do whatever you want. The demo is deployed to Netlify. It's live at react/auth0/demo.netlify.app. It's such a long name. That's it. You have the steps for how you can replicate this project.
[16:44] That's it for today's talk. Hopefully, you found it useful. Definitely, let me know. Feel free to reach out and ask any questions on Twitter. That's where I'm most active. If you have time, feel free to check out my YouTube channel. Just go to http://mahmoud.codes/YouTube, and you will be redirected.
[17:03] That's it. Thank you so much for listening and watching and huge shout out to Egghead for hosting this event. Have a good day or night, and I'll see you around.