Tutorial - Login with Google using Passport.JS in a MERN Web Application

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
okay folks I wanted to make a quick tutorial uh that I couldn't find when it came to working with passport.js and probably the reason it didn't exist before is there's so many ways to work with passport but what I have is a M Stack app uh that is bellel running club.com it is deployed to the internet and it is working with Google oo 2.0 and so I can hit SLO /g gooogle on my website I can authenticate using Google and it's just going to spit back some some Json data telling me about who has successfully logged in and so I couldn't figure out how to uh find the tutorial U to to have a bare minimum number of steps how to set this up with a M Stack application so I wanted to create that today again this is using passportjs in a Express react in node obviously my react front end is not completely built out this is a backend solution working with Express and database not only do I display this user on the page but I also on my database save that user information in my user collection okay so uh bare minimum number of steps here they are step one you will need the right dependencies so to go here to go to the documentation uh and look at all the strategies I should say click on view strategies I am using passport with oo 2.0 and so this is going to allow me to connect to Google so here's my dependency of course I will need in addition to this you need passport so you need passport dependency which is this command here right of course it's just npmi passport so bring in passport as a dependency at your terminal mpm I passport then you're going to bring in once you bring in that dependency you're going to bring an O off 20 so bring that command in step two bring in that command uh step three and uh I already have this installed um so needless to say don't worry about that error message step three is to bring in Express session and this is going to allow us to save our user into a cookie so that our session will persist even if they close the browser uh the user will stay logged in so npmi Express session those are the three dependencies if I open up my package Json you will see these three dependencies um that I'm working with now everything else the only other prerequisites I will say you should be familiar with the EMV package to store variables environment variables in the EnV file as I have here and I'm also I'm choosing to use mongod DB client um um package and so uh I that's called the driver is what that's called uh and I know there's other ways to connect into your mongod DB but I'm just using the driver as opposed to some of the other tools that are out there um other than that uh the code is not crazy complex okay you're going to notice and I'm just going to kind of bring in I'm going to highlight the code that was specific to this I bring in passport I bring in a Google strategy for passport okay I bring in some database functions to save users to a database from a from a database file so this is like a custom this is a file that I wrote okay these are bringing in some methods from the dependencies and the same thing here this import session from Express session okay so these are the Imports now once I boot up an Express app variable um we are ready to configure passport and so there's a few things to configure passport the F the first thing when you do passport. use you have to say two arguments the first argument is you're using a Google strategy in order to use a Google strategy you need a client ID and a client secret now you know what you should do at this point is go to your hosting provider of choice you know mine was gcloud and I said how to get a Google client ID on gcloud well it turns out in order to get a client ID on gcloud here I'm on my cloud counil I had to go to my apis then I clicked on credentials and I had to create credentials right here and this allowed me to create an o 2.0 client ID and it came with basically a string that was my client ID and a string that was my password okay so you have to configure this now there's a couple of what I would consider to be confusing steps um the first and I'm taking this off the screen is what are the URLs that I had to allow is authorized JavaScript origin and so so there's three I'm just going to put this in notepad I have three URLs that I want to kind of talk about why I have each one of these threes on here Bell running club.com well that's that's where the site ends up that's pretty self-sufficient um Local Host 5000 that's my testing that's my local environment so I put both the live environment and my local environment as another authorized JavaScript origin and here's the third that I add added um this is the URL the gcloud gives me for my um Cloud run service and so I have a cloud run service that's hosted at this URL that basically redirects to Belleville running club.com so um I put all three of these now the next section when you're creating this client ID is what are the redirect URLs or Uris okay it's the same three sites with this sloth gooogle callback okay and so I put all three of these in the authorized redirect URI okay and then I click on Save and that's what I needed to create a client ID and a client secret once I had a client ID and a client secret let me clear this big red error message M and get that terminal out of the way and kind of zoom in here once I had a client ID in a secret I save those in environment variables and I access them out of my environment variables using process.env okay now this callback URL is ultimately this app URL is just www.bell running club.com or not even W just B running club.com okay so probably could have just kept that the string didn't really need to put that into a variable but I I put it into a variable because I'm going back and forth between testing and live um and so I change that variable from time to time so that's my Google strategy get a client ID get a client secret callback URL is just a static URL this is this URL a call back is the function that runs upon completion of authentication so once the user authenticates it's going to send you to this route on the back end sloff SLG gooogle callback remember that because that's coming up now the second the second argument here in my Google strategy is basically what happens when the user is successful you can kind of see here I I run a little bit a simple if else if the user already exists we don't do anything but if the user doesn't exist in my database I call this add user function and saves my profile the entire profile object into my database that is this right here again I I can show if I were to delete this and reauthenticate if I delete this object delete kind of refresh it's gone I go back to Beville running club.com I reauthenticate right um it will resave this user into my database upon a successful login and if I do it again you know it doesn't save the user over and over and over it just saves the user one time when the first time they authenticate so that's cool um so that's all this if else done uh if else does and you can kind of see here at the end of this Google strategy it says return done profile that that uh more or less takes you to the next method um in the middleware um so that you know the the passport strategy will then run this call back URL it's kind of where it goes next okay um these two methods are what I consider to be boiler plate um to help you write serialize a user save a user is the way you could think of this save this user object into a session um and read a user out of a session okay so we're we're using the serialized user and deserialized users of passport in order to save user information into a session which is ultimately in that cookie um to demonstrate this cookie here I have a session ID S ID that if I were to close this browser Tab and open up Chrome and paste okay uh the the user is still logged in I close the browser I reopen the browser user still logged in because they're saved in session and saved in this cookie that's what those lines of code help me do save the user in the session or read the user out of the session um you know depending on whatever operation needs to be done one more um line of code to kind of get that session to work when you're setting up a session again keeping in mind this comes from the express session dependency that we brought in okay this session is configured right here and the important things here are that um we're getting a session secret from our environment variables uh recommendation there is just to have a long string that's not easily guessable or hackable so just a long string of characters uh resave it save uninitialized again don't dive too deep into touching those leave those the same but here this is the duration of your cookie which is basically one hour that's uh th milliseconds times 60 seconds is 1 minute times 60 Minutes is 1 hour so those three lines kind of help our sessions work then we run this initialize middleware app.use passport session get everything up and running and that's it for the middleware the next section that of methods to write are for your routes and so I'm looking here at line 72 this is the initial route this is a backend route that you might use something like um uh axios right to call this URL uh when the user clicks the button to authenticate with Google uh so anyways at some point you're going to call this URL to kind of initialize uh the Google passport authentication process so when you navigate here on the back end we call Passport authenticate with Google um you know for my own learning and understanding you know I think there's some different options that might be worth checking out here um because quite honestly if I look at the information that's given to me with this code it's not a lot of useful information you know I got a username I got a like an ID coming from Google um I've got like a profile picture that I can use but there's not a lot there I can't I don't even have the user email address okay so I would experiment here uh on this authenticate method ways to see if Google can give me more useful information about about the user you know ideally I'm at least getting their email address because I don't have that right now the way this code is configured so this triggers the authentication process and then it goes here on the backend route of off Google call back again this was the URL that that the client ID asked for right it wanted to know that that backend route um that that you need to navigate to after you trigger this authenticate method okay and here you've got two options like what do you do upon failure and what do you do upon success so here's the route what do you do on failure and failure I redirect to home and then on success I redirect to profile well if you look at the SL profile route SL profile I say hey if the user is authenticated then stringify the user data and put it into uh a pre- tag and just display it on the page okay so again no front end built out for this just yet just got the back end working to work with Google authentication and basically in the event that it works it just puts the user information on the page otherwise it redirects you to home and then of course we want a little logic here to log out as well that destroys the session and clears the cookie and redirects home right so a slash logout route as well and that's what it takes and so um at a high level I wanted to make a bar bones what does it take to get passport working with Google oo 2 and that's that's what it took me to figure out hope you enjoy
Info
Channel: Evan Gudmestad
Views: 722
Rating: undefined out of 5
Keywords:
Id: NrO0W0rqFB0
Channel Id: undefined
Length: 16min 10sec (970 seconds)
Published: Mon Mar 18 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.