React and Auth0 Crash Course and Workshop

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
there are lots of different authentication tutorials out there but sometimes it's hard to put them all together so in this video we're going to cover everything you need to know about react user authentication with auth0 authentication authorization private routes calling apis access tokens id tokens everything you want to know all right so i'm going to start here by referencing a few pieces of material one and this is kind of what we're going to follow for the most part in this video is the complete guide to react user authentication with auth0 now this is created by dan on the content team this is an amazing article and more or less what we're going to do is kind of run through the steps as he has set up in here but we're going to do this a little bit differently and what we're going to do is tailor this a little bit towards kind of a workshop environment where if you are following along with the author react workshop link below the repo might actually change but the link will get you to the right repo so make sure to check that out inside of this repository it's got both a front end and a back end folder inside of it and so we'll need a back end to be able to call api so that's just a regular express server that we'll be able to run so that from the front end we can send access tokens and make a request and we'll cover what access tokens are here in a second but it's got the front end it's got the back end as well as if you look in the article it's got about seven different steps here of what you need to do to complete this tutorial and inside of the repository it's got a branch for each one of those so step one branch will be the code that you will use to start at step one which in this case is right here so uh the couple of examples in here um that you will need to know or a couple of transformations you will need to know is inside the blog post it references two different repositories for all the work that you will do but in this case this is in the same repository but in two different folders hope that makes sense so let's go ahead and get started the first thing that we would do here is actually grab the starter code now again inside of this blog post it's going to reference a repository specifically for the front end what we have however is one repository that has both of these things in it so if i look into here i've checked out this repository again the right here link below in the description this repository here and then i've checked out the step one branch so this will make sure that i'm ready to get started and then i've got my front end and my back end folders ready to go so that would be the first step the second is to install the project dependencies now this is specifically talking about the front end in this case so i'm going to cd into the front end and i'm going to do an npm install so for that react application i'm going to install all of the dependencies and there's not a ton of new stuff in here there's a few things actually that's the back end let's look at the front end it's using just your react dependency so nothing especially creative in here so we can close that out and let that install and then we'll continue to go on so we've got our starter code now we need to connect react with all zero which means you have to start by signing up with a free account in all zero now with the free account we've got a pretty uh substantial free tier i would say and it'll allow 7 000 free active users now keep in mind active is users that have logged in in the past month so you can have a hundred thousand users but we only are judging you based on the active ones so what we're going to do is create a new application inside of auth0 so your dashboard may or may not look a little bit different than mine but you should have an applications tab here and you can create a new application and we'll call this my react app it doesn't really matter what you call it and since we're doing react here this will be a single page application after we create this there's a few things we need to do one if you're going through the documentation you could follow the quick start here but you're following this tutorial instead so if we look in settings there's two not credentials but two things that we need to know the domain and the client id we'll use those in a second and if we go back to the step-by-step guide it's going to walk us through setting the allowed callback urls the allowed logout urls and allowed web origins now just to be clear on what these are the way this authentication workflow happens is inside of the application you trigger a login action which will basically redirect the user over to the authentication server which in this case is all zero auth0 will handle the authentication the actual login process and then redirect the user back there's some extra things that go on in that process but the output of that is sending the user back with an id token and an access token we'll talk about those more in a second so to do this redirect stuff off zero needs to know from where can people access all zero to do this login process and then where can they send them back to so we'll update the allowed callback urls and the allowed logout urls as well as the web origins with this localhost 4040. so let's scroll down and go into the settings here and our callback urls log out urls and then lastly domain origin most importantly make sure to scroll all the way down and click save changes here so those things are saved now the next step is we'll need to use this domain and client id if we kind of scroll back through the documentation here it references having an environment variable file inside of your front end where you can put these two different credentials and in mind i've already got one created so inside of my front end what you will do is create a dot env here i'm actually going to get rid of a few of these extra ones and then get rid of these credentials so that i can start just from where you are so you will need to create a dot env file inside of that front-end folder with two properties react app all zero domain and react app also your client id and again looking back inside of your application here is the domain so i'm going to paste that one in and then here is the id so we can paste that one in as well so those are our two environment variables that we will need now since these are prefixed with react app we'll have access to those inside of the react code that we write all right so we've got those things set up and in place the next step is to actually use the sdk the react sdk so i'm going to copy this npm install command and make sure i'm in my front end directory and do paste that in npm install and then the group or organization is at auth0 slash all serial react so that will install the package that we will use to then work with this application now the way in modern react this will work is we're going to create a provider or actually use the provider that all xero gives us and then wrap our application with that provider that will give us access to anything about the user that we want to know is the user logged in user information the actual user data whether or not we're loading the user if the authentication process is finished all those things will be accessible through this also provider using hooks inside of react and this sdk takes care of most of that stuff for us so the one thing we will do is we'll we're actually going to create a new file here so this is the os0 provider with with history so we're going to take the austere provider that they give us and then just give it a little bit of extra information about the router inside of react so this project is already set up to use react router so let's go into source and then we want to create this inside of auth so we'll create a folder in source and source source called off and then just since this is kind of a long name here i'm going to paste this name in so this is the all zero dash provider dash with dash history js let's paste that in and then the cool thing is from here too this is basically just a copy and paste and i'll paste this in and then show you what we have so let's copy and paste this snippet and let's throw it in here so we are using the also your provider again from that osceola package we are getting the domain and client id from environment variables those two credentials that we just used and the main thing we care about is getting this history object from the use history hooked from react router dom now this enables us to make sure that if we wanted to we could redirect a user to a specific url we can access that history object and then push on things so in this case if there is a return to url it will send them there otherwise it would just send them to the root of the application and it's able to use that history object to do that so the last thing is we configure the osceola provider with the domain the client id redirect uri which is basically the root of where this application is hosted and then we have the on redirect callback function that's defined up here so we have that in place now the next step if we look down a bit further is to make sure that we're actually using that all zero with provider or all zero with history provider and if you want to know more about that there's a little more detail in here but basically what i want to do i'm going to take this entire snippet from the documentation there and go into the app.js actually the index js and i'm going to just paste this in now the only real thing that we changed is we made sure that the router is a parent of the austere provider with history and then inside of that is the app that way the aussie row provider with history will have access to the router object because it's wrapped inside of it and then everything inside of the app will additionally have access to the hooks that come along with off0 so we could go ahead and start this application let's do an npm start here this will start it up it's by default set up to run on port 4400 so usually you're used to seeing react at 3000 we just kind of are choosing a separate port here to make sure that you don't have any conflicts so this will start up at 44 or 40 40. and it looks like i missed a line in this snippet above to make sure we export that all sear provider with history so we were trying to import something that we didn't actually have access to yet so let's give this a refresh and now we should see that this actually comes together well so we've got this application configured to work with all zero but we're not actually triggering any of that interaction so what we need to do is actually come into back to our documentation here and now since we have this setup now we actually need to add login and log out buttons and the good thing is this documentation is going to give us some snippets to go along with this so i'm going to start by copying this login button here and we're going to copy and paste some snippets but we'll talk through what they're doing in this process so inside of components this is the login button js file and then we'll paste this in so all we're really doing here is creating a button and then it has an on click handler that calls this login with redirect well where does that thing come from this comes from the use all zero hook so you can see how powerful this hook is already and you'll see more of this in a second where if we want to trigger a login process we can import that function from this hook and then just call it and we have access to it that way all right so there's our login button then we'll do something pretty similar here we'll have a sign up button so this is going to be a little bit different very similar but it's just going to have one property that's different so let's add our sign up button in here sign up and let's paste in this snippet so the only thing that's different here is it's calling login with redirect but it comes with this screen hint here to show hey instead of logging in directly take me directly to the signup process so that'll be our sign up button there and the last thing last button specifically that we'll want is the log out button so let's copy the snippet from here and you can probably guess it's going to look really similar where it's going to take the logout function from the aussie row hook and then call it directly so log out like that and then we'll go ahead and paste this snippet so again you get the logout function from this all0 hook and then you're able to call log out and then define the return to to make sure we just send the user back to the root of the application so some pretty cool hooks there the last one thing that we can do or the last thing we can do in here is kind of put all those things in one spot so in this case in this case we want to decide whether or not we want to show the login button or the log out button i think you'll appreciate how cool this is as well so let's add our authentication button js and you could break this down into any way that you want but this is a pretty clean way of doing it where you have your login you have your log out and then in this one we're using our hook to determine whether or not the user is logged in so if the user is authenticated we let them see the log out button if they're not logged in we let them see the login button so there's our authentication button which combines those two and now scrolling back down we can create kind of an off nav that we can use that will show all of these things so again we're breaking these out pretty finely you can break them out however you want but in this case we're going to create an off nav and then paste in that snippet here all right and this is going to come with its own styling using the bootstrap classes here but it shows our authentication button which will toggle between logged in and log out depending on the user status the last thing to tile of this section together is we're going to import the auth nav and then make sure to display that inside of our regular nav bar so let's open up our nav bar and that much will change from this but i'm just going to paste in this new snippet so we're going to import that off nav and then show it right underneath the main nav so if we do a refresh on our page we should come over and we should see that now we have a login button now remember all we've done so far is we took the starter code we did an application inside of all zero used a couple of credentials inside of environment variables and then we did a couple of steps to create these login logout buttons and showing and hiding them and that sort of stuff but all of that power really came from the off zero hook so in the log out button from the all zero hook you get log out for the sign up button you get login with redirect for the login you get log in with redirect and for the authentication button you're checking to see if the user is authenticated so now that we have all this stuff stuff set up we can import anything we need related to authentication from this use all zero hook all right now that we have all of that in place let's come back to our application and give this a shot so we have our login button so let's do a log in here this should redirect the user or you yourself over to auth0 in this case i've already used this tenant before and i'll see your so i already have an account if you don't have an account you can do the sign up here with email or password you can also use the built-in sign-in with google now the one thing you need to know is if you do the sign-in with google it's using test credentials inside of all xero so you might have some issues in it tracking your state of being logged in so i would recommend not doing that right now and then let's log in i'll log in with my existing account and then after you do a signup you should get to the same point and here no i don't want to save that username and password but now you see i've got the logout button so let's try this again let's do a log out here and this should log us out you see that button is getting updated so those hooks inside of all zero or inside of react four off zero are working and we could do just to make sure this is working let's do another login here so let's do the same thing to make sure that we're still tracking this flow and that log in works now we see the log out so the power of this is all inside of this react sdk which is giving us these hooks now all the stuff that we did with creating these different buttons all almost all of that was react except for going in and actually getting the different hooks from the uzos zero hook that we needed like login like log out that sort of stuff so we're making really good progress in here if we scroll down to the next step the next step the retrieving user information now that we have a user that is logged in now we want to start to display some information about that user just to show you what we get back and where this information comes from is from the id tokens in all zero so after this authentication process is complete what you get back is an id token and an access token we'll talk about the access token here in a second what the id token is this is basically a token that shows personal information about the user or profile information about the user and it's important i should specify personal information is not the right word because this is not secure this is not security data this is not stuff that needs to be secured this is kind of public profile information so what we want to do is open up this profile component and then we want to get some of this information from the user so let's take a look at the profile page here if we scroll up to the top we're not actually importing anything yet we're just kind of displaying some dummy text so let's go and grab this snippet and then i'll talk you through what is in here so let's grab this and let's select everything in profile and then paste in a new code so not a whole lot has changed here other than the fact that we're actually importing the use all zero hook again we've seen this a couple of times and then from that uzos zero hook one thing we haven't seen is it gives us a property called user so ideally in the next step we'll make sure that no user can get to the profile page the profile route unless they are logged in so then we can expect a user to actually have some information here so you can see we get back a name property a picture property and an email property and then we're just displaying that information we're displaying the image the picture inside of an image tag the name and then the email and then the last thing we're doing is taking all the information that user object and then we're stringifying it so that we can display it on the screen so you can see all of that metadata so with that in place again just using this one hook here to grab the user information and then displaying it appropriately we scroll back over and we come to our application and looks like i'm missing the export again so we got to be careful in copying those snippets but when the export is there now we can click over to the profile page and you see there's my email then there's my image and you can see all the information that comes with my profile now again this is not private information i'm not worried about you having this information this is kind of public profile information that in your application you can use to do whatever you want now the one thing that is pretty important here is this sub property that's basically a unique identifier for a given user inside of all zero so if you're then associating user data in some sort of uh database that you run yourself like if i am creating blog posts or something like that this sub property is the unique id for the user that would be useful for associating which records go with a given user all right so let's scroll over i think that will do it for the profile page just kind of walking you through what all has done there now the next thing is let me just show you what this looks like if i go to log out here and then i'll come back to the root of the application even uh well i was going to say even though the profile button is not there but it actually is still there so let's click on the profile button and now you see it's throwing an error and because it can't grab the name property of a user that's not actually there so we uh we grab this user property and then try to get the name property off of that but there's no user uh we're not logged in so we want to prevent that we want to prevent people from coming to this page unless they are logged in and there's a couple of different ways you can do this there is a higher order component inside of the osceola react package and so you could use a higher order package or higher order component to export our profile component but alternatively what we really want to do is create our own component a private route component that we can then use instead of a regular route component so we'll scroll down a bit to see what this looks like and now we get to the create a component to pre protect react router path so this is going to be the protected route js file so let's go into source into auth and then we'll have a protected route dot js file and then we'll go ahead and copy in this snippet here so i'll copy this in and then we'll look at what it is doing so it is grabbing the route component from react router dom it's grabbing the with authentication required wrapper from all zero and then also the loading a loading indicator that is inside of components and then index so that thing is being imported here from the actual loading component there so let's come back to our protected route and basically what this is going to do is it's going to show uh our component the component that you're trying to show if the user is logged in in the meantime while it's redirecting it will show a loading state so with this in place this doesn't quite do exactly what we want because we've created the protected route component but we aren't actually using it yet so let's open up our app.js file and then now instead of using this route component we want to use our private route component so i'm going to type in protected route and i'm going to get a little bit of intellisense in here in vs code of an auto import so i'm importing that thing from that auth directory from where we just created and then i'm going to say both of these things are actually going to be protected routes our external api as well as our profile page all right so let us save this and what we should see now it actually happened before we could actually get there so let's try to do this manually let's refresh on the profile page this should show that loading indicator that you saw then redirect this over to the to the login page in all zero this is a great way to be able to protect your routes to make sure that people can't get there unless they are actually logged in all right now that i'm logged in i should have access to the profile route notice also that that directed me right to profile so this setup that we have is intelligent enough to know what url we were on and then redirect us back to that page so we should additionally have access to this external api page as well these are both protected routes but we are logged in so we should be able to get access to them all right moving down to the very last section this section is about calling an api now we talked about there's two different tokens that you get back in this authentication process you get an id token and we use that to display basically public information about the user then you also get an access token now access token in this case is we want it to be in the format of it doesn't have to be but we're going to use it in the format of a json web token and that's just a format to kind of encode pieces of information but the token itself is validatable or verifiable so what's going to happen is we're going to get this access token then when we make requests to our backend which is going to be the backend project inside of this repo we make a request to that api we're going to send along our access token and that access token will prove that we should have access to be able to access or request make a request send a request to that api endpoint so let's go ahead and look through the documentation here it talks a little bit about how do you make your api call secure passing that token uh how do you call an api that sort of stuff then it walks through cloning that back-end example now remember we already have this so let's open up a new terminal window and then inside of the terminal window i'm going to cd into the back end directory now that i'm inside of this back in directory just like it had inside of the instructions after you get into it now we need to install those packages so this will go ahead and install all the packages that we need and let's close out all of these files for the time being and let's look at our back end so inside of our back end we've got a few dependencies cores for being able to test this stuff across different domains dot env package for using environment variables express for our server framework expressjwt for helping us validate those jwts those access tokens as they come into requests helmet and then jwk jwks rsa so again these two these uh jwk s rsa and then express wt are two packages that are gonna help us do this authentication process or really authorization since we're verifying access and if we look inside of we're not gonna change any of the code in here but inside of our index.js you can see we create a new express app we get access to a couple of things in here we create our we get the router and then we use these different routes but but i want to show you how we're checking to make sure users have the access or can only get access to the things that they should and this is inside of the messages router file so this messages router file defines our different routes for messages so public message protected message one doesn't require any access token to be sent the other the protected one does and so this check wt function here is a middleware function that will check the incoming jwt that access token and make sure that that it is a valid jwt now this thing comes from the auth z check w check jwt and if we look in here we see that we're basically just configuring two things one is the jwt object from express jwt the other is for the secret property we're then configuring the jwks rsa now you probably don't need to or want to know all of the details about this but what jwks stands for is the json web key set and what this is any authorization server that implements oauth2 and open id connect will expose a url here and you can see it looks like slash dot well known slash jwks.json and what that will do is it will show what the public keys are that can be used to verify the jwts that were generated with a secret key and that's how this rsa stuff works is with this public private key combination so we're just configuring this to say hey this is where you can actually go and get the key that we'll use and then we use our audience as well as the domain to go ahead and configure this stuff all together and then we export it and then that's what we're using as our our middleware inside of the one particular endpoint that we want to protect which is this protected message endpoint all right so let's continue to scroll down the one thing we'll need to do inside of auth0 is to add an api and off zero so we have a front-end application our react app we have that configured now we want to create an api inside of all seo to say hey this is something that we're going to send access tokens to and there's lots of benefits that come with that you can do permissions and roles and all sorts of stuff but let's just start by creating this inside of the dashboard so inside of this dashboard going over to apis let's call this react workshop api and then we have a specific identifier in the documentation here that we can include so express dot sample and an identifier here is not a real url it's kind of an arbitrary one but it's a way for us to define who we're sending access tokens to and then for that server to then verify that an access token that it receives was meant for them so that's the identifier that we're going to use in this case so we'll create this api with that thing in place let's continue to scroll down and now we'll need to set up our environment variables inside of express so let's come back over to our source code now let's look in continue to look inside of the backend project and there is a dot env.example that's already checked in here so what you can do is you can copy and you can paste that and then you can rename this file to just.env so there that is so we're going to start with two things two properties are already filled in 6060 is the port that this server is going to run on by default 4040 is the port that the front end is running on by default and then we have our all zero audience and domain now if we scroll down they will show us that the audience is basically the identifier of the api that we just created so back in off zero inside of settings here is what we just typed in in our identifier now we can just take that and copy it as our audience and if you think about it this way we're sending access tokens to an api so when we send that token we have to specify who the audience is so since we're sending to the api that we just created the audience is going to be the identifier of that api and then we'll also have the all zero domain so we can actually grab this from the dot env from our front end and then copy and paste assuming you stayed in the same tenant you will have the same domain here so i can copy that in just as well all right with those couple of things in place we can now go ahead and actually start the server so let's make sure that we're in our backend directory and then run an npm run start and this should start up that express server and it's up and running and what we'll need to do is also open up the front end and then be able to start that as well but we'll need to make a couple of changes there so let's go ahead and get into this where we'll cd into that front-end directory and now if we scroll down we need to update our configuration inside of our front-end just a tad to now add an audience to the configuration so let's open up the env for the front end now and there's two more properties we need to add we can copy these from these examples in here we need to add the audience and then the app server url so if we look at this audience here this is who we're sending the token to so this is the id identifier of that api that we created inside of all zero and then lastly the server url is the url for the server the backend server that we just kind of worked through configuring so we'll save this if you still have your front end running you'll need to make sure that you stop your front end because this audience property is going to make a big difference here but for that thing to take place we need to actually update our configuration of our object so what we'll do is we'll grab that audience property and then we'll use it inside of the configuration for the provider so let me copy this little bit here and we'll open up our off zero provider with history and so we'll paste in the audience here so we're getting the domain the client id and the audience so we've got those three things and then we're going to actually use that audience so we'll pass in this property to the os0 provider now this has a big implication in the source code because now that we're specifying an audience all xero will now send the access token you didn't know this before but it wasn't in the format of a jwt now it's going to send this access token as ajwg and we'll see that here in a second so we can save all of that stuff if we scroll down you'll have a little bit more explanation in here of how all of these configurations and workflows work and that's great but let's go and update the external api file so there's a decent amount of code in here i'm just going to copy this and then i'll explain as usual what we're actually doing with this code so let's copy this and then let's paste it into the external api file and let's just paste all of that in now if you remember on that external api page there's two buttons that you can click one is for a public request to the back end and another is with a protected request so if you look in here we're tracking a message that we want to keep track of we have our server url which comes from from that environment variable which tells us where we're going to send this request and if you look down there's a call api function which makes a request to that server url slash api slash messages slash public message and this is a regular fetch request we're not attaching any tokens to this thing because this is a public request it should work regardless but if you notice we also imported the get access token silently function from the user zero hook what this thing will do is allow us to actually grab the access token that came back in the authentication workflow and then use it and the way we use this and this is a pretty common thing if you're sending access tokens as bearer tokens what you do is you grab that token in here so we we call get access token silently and then inside of the api request now to the protected message endpoint we include an authorization header and then we have the properties bearer space token so this is the way that we're going to pass our access tokens is inside of this authorization header and again bear and then space and then the actual token and then the rest of this is just kind of the same stuff that we had where we display those buttons and then we're able to display a message that comes from the back end and then display that on the front end so in this case with that running now we can do an npm run start on the front end so we've done that before and let's just scroll down and make sure we're not missing anything inside of here this kind of talks through that same idea and then auto reload on this page so we'll let this go ahead and reload our application and i am now logged in so i can go to the external api page and there's a get public message and i get private message or get protected message so let's look at the network tab here do it xha xhr request and let's do get public message and uh you can see that this doesn't have an authorization property inside of header so it doesn't have that it doesn't need it and it says this api doesn't require an access token so that works well the get protected message however this thing will require that access token and remember that's because we use that check jwt middleware in here to make sure that that access token is not only present but is also valid and then it returns back this message saying that you've successfully validated the access token so it worked and if you look inside of the request inside of the request headers you can see the authorization header with the bearer space and then this big long token and just for your awareness if you're curious you can actually copy this access token it's a jwt so you can go to jwt io to decode this thing and actually see what's in there and there's not really any private information in here and there should never be private information inside of a jwt because of the fact that you can do this but you have your header information and then your body and in this case notice a few different things the issuer is the domain of the tenants that we're on so that ought to look familiar the sub is the unique identifier for the user and if you look at the audience this is who we're sending or who we can send this access token to and remember express.sample is the identifier for the api that we created in all xero so when it receives a token it can not only verify who the issuer was making sure that it came from the right place but it can also verify that the token that was created was meant to be sent to it that api which has this identifier of https colon slash express dot sample and that's the majority of the stuff that we need to know about inside of this tutorial and i will walk through kind of a recap in this conclusion here but i think this is a really great example of not just how do you get a user logged in but how do you get information about a user how do you protect your routes inside of react how do you also then get an access token send that to a back end and be able to validate or be able to verify that you have the ability to make that access or at least the back end is able to do that thing so we talked about a lot in this tutorial i hope that you enjoyed it again you have the resource of the repository with the step-by-step branches you also have the resource of the complete guide blog to go back and reference as well let us know in the comments what you think how you're doing hopefully you enjoyed it and i'll see you in the next one
Info
Channel: Auth0
Views: 15,779
Rating: undefined out of 5
Keywords: react authentication, react authentication crash course, react authentication workshop, react tutorial, auth0 tutorial, auth0 react, auth0 explained, json web tokens, access tokens, oauth2, openidconnect, id tokens, protected routes react, react router private routes, react call api, reactjs crash course, web development, authentication auth0, react security, how to add authentication in react, how to setup auth0 in react
Id: PYWS-4CXETw
Channel Id: undefined
Length: 36min 4sec (2164 seconds)
Published: Fri Nov 13 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.