Login / Signup / SignIn with Google | OAuth2.0 | Using React and Express JS

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome back to my channel thanks for popping in if you're new here please like And subscribe for me if you find this content helpful hit that notification Bell so that you don't miss out on the next video comment below with your thoughts or topics you'd like me to cover and check out my website consultingninja.tech with that out of the way let's get right to it I've been doing a mini series on authentication and I want to make sure that I don't leave out my react and express folks so I'm going to show how to use Google authentication when you are using react and express I will leave links in the description of this video for the basics of setting up a Express backend as well as a Veet react front end I'll also leave a timestamp if you want to skip the Google developer console setup and just get to the coding portion what we are going to make is this it is a sign in button that you can click and it will take your users to a Google page if they're already signed into their Google account they can just select it otherwise they would enter their username and password and then when you click that button it will redirect back to another route we'll take that request from Google and authenticate them using the Google auth library npm package and then as a bonus I'm also going to show how to Ping the info API in order to get the name and family name as well as the picture sure for that user if you want to see how to do this stick around that's what we're going to do right now the very first thing that you need to do is set up your Google developer console you can just go to Google Search and type in Google developer console and then click the first link that comes up it should be the console.developers.google.com you do have to have a project in order to do this so if you don't have one click create project all you really need here is a name you don't have to choose a location and the name is only important for you if you've already created a project you need to go into the actions menu and click settings once you're inside of your project you'll be presented with a dashboard you need to go to the navigation menu and all the way in the top left hand corner and select apis and services and then go to oauth consent screen you can only have one consent screen per project and I already have one since I've been showing how to do this with other Stacks so I'll just go through and edit this one you do have to choose a name for the consent screen this is what's going to be presented to the users as well as a user support email if you want to give a logo you can it's not required but it does make it look better the app domain information is not required here but authorized domains is you can just put localhost.com if you move to production then you would want to put whatever your domain is.com the last required piece of information on this step is the developer contact information and you can use the same email address as the support email the next step and this is the really important one is defining scopes for your consent screen the Scopes are what you're telling your user you're going to do once they give you access in order to authenticate using Google you have to have the basic three this will be empty by default so you can just click add or remove Scopes and select the first three options user info dot email userinfo.profile as well as open ID another thing to keep in mind is that when you're using the oauth 2 client you have to list out the Scopes one after another in in an object that you pass in that is in the form of a URL where all of them start with a base URL of https www.googleapis.com and then this picks up from there so you can come back to this screen when you're setting up your Scopes in your back end and just copy and paste any ones out that you need for the sake of our video again we're just authenticating so we're going to use these three when your Scopes are defined click save and continue when you first set this up your project will be in test mode and while you're testing the only people that the consent screen will work for are users that you have listed as test users so you need to make sure that you have whoever you're going to be testing this with listed here in the test users list once you have all that done just make sure that everything is correct and click save so with your consent screen done you need to set up credentials so go to the credentials Tab and click create credentials these are going to be oauth client ID credentials and we're going to have an application type of web application the name here doesn't matter this is just going to be for your reference it'll show up in the list of all your credentials the part that is important are these two pieces the authorized JavaScript Origins are where you're going to be pinging this from so basically where the request is coming from and the redirect Uris is where the requests are going out to and you can have multiple set up for both of these you can have multiple places that the origin comes from and you can have multiple places that the redirect goes to for the sake of this example we're going to be coming from http localhost 51.73 that's our Veet front end and then we're going to be going to http colon slash slash 127.0.0.1 Port 3000 slash oauth so be sure to give that a save I'm going to be using credentials I already created because the note here on the bottom says this can take five minutes to a few hours and we don't have that long once you click create though it's going to present you with this screen that just says hey we created your client and the two pieces of information that you're going to need from here in order to make this work are the ID and the secret so inside of your Express backend you have to make sure to have dot EnV installed because you're going to need environment variables so be sure to do an npm install.env you're also going to need to install the Google auth library so do an npm install Google auth library Google auth library is the official auth library from Google so no worries there inside of your code make sure that you have dot EnV installed and make sure you have the Google auth library installed create a new environment variable and then I like to make sure that these match so I would just do client underscore ID equals and then you can copy and paste those out of your console so paste that in and then you need the client Secret client underscore Secret and you can copy that as well so that's the last thing that you need to do in your Google developer console the rest is going to happen in the Express and the react portion so we can save this environment variable we're not going to use any views so we can delete that whole directory inside of routes let's go ahead and just repurpose these we can rename this one to request this is the route that's going to generate an auth URL using the auth client the auth URL is how you ping Google to generate that request and then the redirect so we need to have Express and router we also need to fire up dot EnV const.env equals require dot EnV and then do the DOT env.config we also need to fire up the oauth 2 client so const brackets oauth to client and that should be a Capital C and we're going to require the Google auth library package this is going to be a post request so router.post and it's going to be an async function so we need to put an async in front of there and then we can get rid of this and what we're going to do here is when we ping this route from our front end we're going to generate a URL and then send that back and ping the URL from our front end and we want to do that because if you redirect from one origin to another instead of getting credentials and a code back Google will package this up in a cross site request forgery token that requires a whole bunch more steps and a whole other package in order to make use of so trust me save yourself the headache and do it this way so what we need to do here is let's do a response.header we need to make sure to deal with cores so access control allow origin this will be our front end localhost 51.73 so we make sure we're not blocked by cores and then Google also prefers you to have this header on there so add another header and this is the referrer policy and what we want to do here is no refer when downgrade and that's because we're testing and we're not using https we're only using http so if you're using HTTP with Google auth you have to have that header on there now we need a redirect URL this is telling the oauth2 client where we're planning to redirect to so const redirect URL and that's going to be HTTP colon slash 127.0.0.1 Port 3000 slash oauth this has to match because when you send the request to Google Google is going to check to make sure that you have that redirect URI listed as we had set up just a minute ago if it's not listed you'll just get an error so be sure that this is matching what you set in your console now we're firing up the actual oauth2 client so const oauth to client equals new oauth 2 client and we're going to pass in the process .enb Dot client underscore ID and process dot EnV y dot client underscore Secret so first the ID then the secret and then the redirect URL now what we're going to do is we're going to use the oauth2 client to generate the URL that we're going to use to Ping Google with so const authorize URL equals oauth2client dot generate auth URL and this takes an object we have to have an access type and for the sake of testing put offline this is going to force a refresh token to be created I recommend putting this on there for testing because this will make sure that a refresh token is always sent so if you're seeing this multiple times then it will look the same every time in production you would only have the access type of offline if you're needing to force a refresh token to be created for scope what we're going to have here is that giant URL I was talking about https colon slash slash www.googleapis.com auth and then we need the user info dot profile and then also the open ID so if you needed other scopes for your application you would just as I said go to the Google developer console and copy and paste the other ones after this lastly we're going to put a prompt on here of consent just to make sure that the consent screen stays open and they have to verify in the affirmative even if they're signed in we don't want this to just get pushed through and then response dot Json and we're going to send an object of URL and authorize URL so now we have a route set up that we can ping to generate an authorization URL and we can ping that from our front end before we create the front end code let's go ahead and set up the route for authenticating that request that comes back from Google so let's repurpose this index.js file and we'll rename that to oauth inside here what we're going to need to do is we'll need all of the same stuff that we needed before so we can copy and paste all this out so we need Express router.env and the oauth2 client I want to show you guys how to get the user information but I want to point out here quickly before I do that that according to Google you should not associate an email as being a person for the sake of Google as far as Google is concerned the person itself is the access token that comes back so you can use that access token to find out their name their email address and such but it is not don't save that email address or their personal information as them because that information can change according to Google so just a note there but let's define an async function here and call this git user data this is going to take an access underscore token and what we're going to do here is do a const response equals 08 fetch if you're not using node 17.5 or sooner you'd have to do the old school version or just upgrade to node 17.5 or later in order to be able to access Fetch and what we're going to do here is use a string literal so use the back ticks and it's going to be https colon slash slash www.googleapis.com slash oauth two slash V3 slash user info question mark and then we're going to add access token access underscore token and then dollar sign bracket access underscore token then what we'll do is we'll do a const data equals oh wait response dot Json and you can console.log this out if you want data equals data and you also could console.log out to response if you want to see the full response the redirect that comes back from Google it will be a git so we can leave that as is but we do need to make the async so add a sync there and get rid of this response.render we're not rendering out anything what we are going to have is a code that we're going to pull out of the params so const code equals request dot query dot code and you can console.log that if you want to see it's just a code that Google is sending back and again if you do this and the code's not there be sure that you are initiating this as I'm sending it up because again if you're not sending it up this way you'll probably get that cross site request forgery token instead and trust me you don't want to have to deal with that you have to get a special public key and Google rotates them just trust me when I say don't don't waste your time with that it's a lot extra work when you don't need to do it so const redirect URL this is going to be that same URL this has to match what we sent originally so HTTP colon slash 127.0.0.1 Port 3000 slash oauth we also can fire up our client so we can copy and paste that could have just copied and pasted both I suppose and then what we're going to do is we're going to do a const response equals 08 oauth to client dot get token passing in that code that was sent back and trust me when I say this as well ignore this they're full of crap I don't know why the IDE is saying that this has no effect because if you hover around here you can see that this is in fact promise based if you don't put the await on there nothing else will work because it's not going to wait for that to come back so be sure you have the await don't listen to your IDE it's full of crap all right now what we need to do is await and ignore this one again oauth to client dot set credentials and it's going to be response dot tokens now give yourself some sort of message here you can say tokens acquired and then you can set your user and that's going to be the oauth 2 client dot credentials you can console.log those if you'd like credentials and you can just pass in user and then lastly Let's do an await and we'll use that function that we just wrote get user data and pass in the user dot access token and then lastly we have to have a catch so catch errors and you can do a console .log error with signing in with Google give that a save now make sure in your bin www towards the bottom you have the port number set up correctly and I always like to add a console.log in this on listening function so that you know the server is running server is running on Port and then I add the port in there and in your app.js you need to make sure that those two routes are defined correctly so we have our auth router which is the routes slash oauth and the request route which is generating the URL for us that is the request router routes slash request then make sure that you plug those routes in so with that you can fire up your node.js backend with npm start now we need to focus our attention on the react portion so inside of this same directory I have my V to react front end and inside of there all we're going to do is go into our source and go into the app.jsx and we can delete all of this out except for the alligator brackets we're not going to use the logo I'll be sure to include the Google sign in buttons into the repository the link will be in the description and there'll also be a link for the requirements you have to follow when you're using these so be sure you follow those requirements we're not going to need the account or set count and we're not going to need the set state but we will need to import Google button and this is going to be from dot slash assets Google sign in buttons web 1X BTN underscore Google underscore sign in underscore dark underscore pressed underscore web dot PNG I think that they gave that a long enough name all right now we're going to define a navigate function so function navigate that's going to take a URL and then we're going to do a window dot location Dot href to that URL now we need an async function and call this auth this is not going to take any parameters but we're going to do a const response equals oh wait fetch and you guessed it we're going to Ping our own back end 127.0.0.1 Port 3000 slash request this is going to generate that auth URL so that we can ping Google and we just need to pass in an object with the method of post now we can pull out our data if data equals oh wait response dot Json you can console.log that if you'd like here and then we just need to fire that navigate function passing in data.url so now we have our functionality done all we need to do now is render out a button so inside of our alligator teeth I have to of course be sure to say welcome to Consulting Ninja I might as well add our H3 and say Google oauth I will leave out the link and we'll just get to the rest for the sake of time I'm just going to render out a button this will be a type of button on click we're going to run an anonymous function that runs our auth function then inside of here we just render our image with the source equal to the Google button and an ALT of Google sign in and give that a save fire up your react front end by typing the npm Run Dev with our front end running and our server up and running now we can click our sign in with Google button we get that authorization URL that we've packaged together with our request route and send that back to our front we then navigate to that using the function that we wrote the window.location.href and that will actually send the request to Google and generate this page I'm already signed into my Google account so I can just select it and then this will send the request that redirect URI back to our oauth route where we pull that access and refresh token out it also comes with a list of the Scopes that we said we were going to use the ID token is just a JWT token this is not the actual ID if you were to pull this apart it would be a whole bunch of information that you're never going to use or or very likely to never use and then here we have the response from the user info that profile request that we sent using that access token there is my name my given name and my family name as well as my picture so there we have it there is Google authentication this time using react and express I hope that you found this video helpful if you did please like And subscribe take care and as always have a great day thank you
Info
Channel: Consulting Ninja
Views: 32,251
Rating: undefined out of 5
Keywords: oauth2, OAuth2, Oauth2, OAuth, oauth, OAuth 2, oauth 2, O Auth 2, o auth 2, google oauth, google Oauth2, google oauth2, googleauth, googleoauth, googleoauth2, Google oauth2, OAuth2 Google, auth, authentication, google login, google sign up, google auth, Google auth, Google OAuth2, oauth2 google, React OAuth, react oauth2, react google auth, express auth2, nodejs oauth2, react node oauth, react express oauth, react express google auth, express, Node JS express, express google auth
Id: 17xwTuidqZw
Channel Id: undefined
Length: 26min 8sec (1568 seconds)
Published: Thu Jun 01 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.