NodeJS & Express - Google OAuth2 using PassportJS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone today we're going to be creating an api using node.js and express we're then going to add authentication to that api using oauth2 with google as an identity provider so i've just created an empty directory here and i've moved into that directory in the terminal i'm going to use npm init to initialize our node project and i'm going to use all of the defaults so now i'm going to open this inside my code editor i'm using visual studio code and we're ready to get started now so i'm going to open up the terminal and we have a couple of things to install first of all so i have one dev dependency so that is nodemon and then i have four dependencies so these are express express session passport and passport google oauth2 and i'm going to be walking through each of these dependencies as we use them and explaining why we need them so now that we have all our dependencies i'm going to create one file this is called index.js and this is our entry point to our application so inside our scripts now we're going to change this test script and we're just going to call it start and we're going to use nodemon to run that file that we just created and nodemon just allows us to restart the server every time we save our file which just means we won't have to keep stopping and starting it manually it'll save us some time so now if we use npm start we can see it's it's running nodemon on that file so every time we save the file it's going to restart automatically for us so now let's get started with our api so first of all we're going to use express and then we're going to initialize our app like that and then we're going to create a route so we're going to say app.get so whenever someone goes to just forward slash we're having a request and a response and whenever someone visits this route we basically just want there to be a link to log in using google because we don't want to show them anything else except that so let's just do res dot send and we can send a href and we're gonna have a link here and this link is just going to auth google so and then let's close our a tag so this is just some html that we're going to return with a link for them to go to this route which we are going to build out in a couple of minutes so now if i do app.listen on 5000 and let's just console.log listening on 5000 if we save this now we're going to be able to go to that route and we're going to be able to see this link so go into localhost 5000 we can see we have this link and we click it it'll bring us to this page we don't have anything there yet obviously um so that's what we're going to start building now so we have this simple route um we also want to have a protected route so let's just say app.get forward slash protected and this is a route that we don't want people to be able to visit unless they are logged in and let's just return hello and whenever they're logged in we're going to have access to their name so we're going to be able to append their name to this to show that we have some details about them but for now obviously this route isn't protected yet so we can visit that here as well but we're going to protect this route and add authentication in front of it so that's kind of our basic api setup now let's start off with the passport stuff to get started so first of all we can see that on this page we can look at different strategies and the strategy that we're interested in is google oauth2 so we can see here we already get some really useful code so we're going to be able to reuse a lot of that um so first of all let's just copy this and we're going to walk through the code in a minute but let's create a new file called ask.js and let's paste that in we're going to change this fire to a const and then we're also going to bring in passport itself and let's just clean this up a little bit so this is our passport strategy for whenever someone is authenticating with google so obviously we're going to have to use our identity provider google and we're going to have to grab a client id and a client secret from them so we're gonna do that now so i'm here in my credentials in my google developer console to get to this point if you just google google credentials and hit here on api credentials you'll be brought to this page so i'm going to walk through now how to create the credentials and i'm obviously going to delete these credentials once i'm finished so that nobody else can reuse them but i'm going to click this create credentials button and we want to create an oauth client id and from here we're going to select the application type so we're developing a web application we're going to give it a name i'll just stick with the default web client2 and now we need to define a redirect uri and this is a uri that we're going to give whenever the user is successfully authenticated our identity provider which is google here is going to redirect them to this uri so this is a uri in our actual application our application is running on port 5000 so we're going to create another endpoint called google callback so now if i create this we have that and let's just click on it to get the details that we need so first of all we have this uri which is this callback so let's copy that and back in our application we can see the callback url is defined here so we're going to pass that in and we also have this client id and client secret and we're also given them both here so let's just define these variables uh in production or in your application you should probably use environment variables so you aren't committing these secrets to resource control like github so let's just make it easy for now and say google client id equals that and const google client secret is the other one so we now have our client id and our client secrets that we're going to use and we're passing them in there cool so this is what happens whenever someone successfully logs in so what do we want to do here this is basically just a middleware function in our express and it's using the passport strategy for google oauth but we don't have a database of users we don't really want to do that here because that's going to make things this video too long so for now instead of creating a user in our database which you would do here you would either create a new user in your database if they haven't logged in before or you would find one if they have logged in before um but for simplicity we're not going to be creating a database here so we're just going to return done and if there's an error it's going to return that and we don't want to pass in the user here we want to pass in the full profile which we're getting from here and if you wanted to do some things on behalf of this user if you wanted them to be able to use other google services you could use their access token refresh token here but again we don't need that so the last thing we want to define here inside this auth file is our serialization and our deserialization of our users so we're going to define that here by saying passport.serialize user and this is going to take a function as a parameter and we're just going to pass in user undone and for simplicity again we're just going to call done and null and user and we're going to do the exact same thing for deserialization cool so we're now actually finished with this aus file so we're ready to use it from our index.js so to do that we're just going to say const art equals require both and i've just realized we aren't going to be using this variable at all we just want this to all be loaded so instead of uh defining a variable for this we're able to just require it without initializing the variable like that okay so the next thing to do is probably define what happens whenever someone clicks this link that we set so this is going to direct the user to auth google so we want to define this endpoint to define what's going to happen when they actually hit that endpoint so to do that we're going to say app.get off google and whenever someone goes here we basically want them to be authenticated so to do that we're going to use passport dot authenticate and in this case we want to authenticate them with the provider google so you could have a link for different providers like google facebook twitter and you could have all these endpoints defined and you're going to authenticate them with whichever the one they've selected so in this case our endpoint is google we're going to authenticate the user with google and then we want to pass in the scope and the scope is basically defining what kind of information do we want to retrieve from the user's profile so we're just going to go simple we're going to say email and profile there's other scopes such as open id which might get you more details but we're going to go super simple here and just use this so if we save this now and we go back to our endpoint that we had here so if we click this it should now direct us to google so this is what's happening here is it's using our google passport strategy and it's using it's passing these details over to google so google knows that it's us as we're passing our client id and our client secret and whenever the user authenticates successfully it's going to bring us back to this callback url so if we click here on one of my google accounts we can see we're getting this error that it cannot get google callback so we now need to define that endpoint and define the behavior of that so let's do that now so we're going to say app.get auth google callback that is the callback url we defined isn't it it's just google callback so we don't need the auth so now as the second argument we are just going to define what happens so we're going to make sure that the users are authenticated with our google strategy and then the second parameter here of this passport.authenticate is defining our success redirect and our failure redirect so our success redirect is the url we want to bring the user to if they're successfully authenticated so in this case if someone successfully authenticates we want to bring them to the protected route so let's go to protected and if there is a failure we're going to use a failure redirect and we could just bring them to a route called auth failure so we already have the protected right let's just define this auth failure right now so app.get auth failure request and response so if someone fails uh if the their login fails we're going to just do res.send i'm just going to say something went wrong so we just have a couple more things to do now i'm going to make this slightly smaller so what we need to do now is define a function that checks if our user is logged in or not so we're going to define that up here we're going to call it function is logged in this is going to be a middleware function so it's going to take a request a response and next to pass it on to the next so we want to check if the request has a user and if it does we're going to bring it to the next uh middleware and if it doesn't we want to send a status back of 401 so this is just saying if the request has a user already we're going to bring it to the next point and if they don't we're going to return a status of 401 which is unauthorized so now in our protected route we want to add this middleware function so here we're going to say is logged in so whenever this route is called it's going to use the is logged in function before it even goes down as far as here and we can see what's happening here if they are authenticated it's going to bring up the next point which would be here and if they aren't authenticated if there's no user in the request it's going to send back a 401 so if we save this now and we try to go to the protected drive we can see we get this unauthorized back and this is because this is because of this four zero one that we're sending so now for the happy path if they are logged in there's one more thing we need to do and that's to allow this user to become part of the request whenever someone logs in and to do this we need some sort of session management and thankfully express provide this for us with this library which we installed in the beginning called express session um and this is actually described in the passport documentation under configure as well um they basically show here about some middleware and they show that you can use express session and this is how you use it so we're actually going to be able to use this here so just under express we're going to bring in session like that and in the same way that they've done we're just going to use it as a middleware here and the order is quite important it needs to be before passport is initialized and it needs to be before passport.session so make sure you put it um you could put it just after your app is initialized here like that so once we have that i just realized that i also need my other parts of the middleware which is passport.initialize to initialize passport and passport.session so you can bring both those in and just put them under here so we have them all together and we can see that there is some deprecated points here on session that we need to define so the first one is resave option and the second one is save uninitialized so it will work without those so we're not going to touch them um but if you look at the express session documentation we'd be able to see what they mean and what they do and what default values they suggest and also for this secret you should probably source this from an environment variable as well and because you don't want to be committing that to your source control so now that we have this let's check it all out and see if it works together so first of all we have this protected route which is still protected if i go back here we still have our link to authenticate with google we're going to click on that and we're going to pick our account and we can see we have an error here error is not defined so let's take a look at that osgs line 14. so we can see here um again this is if we had a database we would be retrieving a user from that or creating a new one um which might result in an error but for now we're just going to set that as null and let's try again so we can see we were successfully routed here to the protected route and it looks like everything worked successfully we're going to take a look here in the developer console and we can see inside the cookies we should now have a cookie and this is a cookie that's being set by express session which is our session id so this is what's allowing us to be logged in so if i was to delete this and refresh my page we can see we now have no session and we're being unauthorized like that so we're actually logged out now um but obviously the user to log it out they're not going to want to do that so we're going to provide them with a logout route as well so let's go down here and let's just define app dot log out request and response and here so to log out the user we're just going to use request.logout and let's just send them a message goodbye great so now we're going to make this a bit nicer so we know that the user's logged in at this point whenever they're here and we know that the request contains some information about the user so let's use some of that information um so there is a part in the request called user and there is a field in that called display name so let's just use that we'll use a template literal here so we can go hello and then we're going to insert our variable which is going to be request dot user dot display name and this is going to show us that we have some information about the user you could explore this a little bit more by putting in a console.log request.user to see what sort of information you get and you could use in your application but i'm just going to do this for now because i don't want everyone seeing my my information we also need to call request.session.destroy and this is going to destroy our current session so doing the full flow again we can click authenticate with google we can log in we get our hello message here we can refresh this page then we can go to log out and we get goodbye and if we try to go back to protected we get unauthorized again so we've successfully been logged out this was how to implement uh oauth2 flow in a express application with using google as an identity provider thanks for watching and i'll see you next time
Info
Channel: Kris Foster
Views: 6,788
Rating: 4.9819818 out of 5
Keywords: nodejs oauth2, nodejs oauth2 google, express js oauth2, passport js google authentication, google oauth 2.0 tutorial javascript, passport js oauth2, express passport authentication, node js google authentication, node js google authentication tutorial, passport google oauth2 tutorial, passport google strategy, express passport tutorial, node passport google oauth, passport js google authentication 2021, passport oauth2 2021, nodejs oauth2 2021
Id: Q0a0594tOrc
Channel Id: undefined
Length: 20min 32sec (1232 seconds)
Published: Sat Feb 27 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.