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

  Рет қаралды 34,212

Consulting Ninja

Consulting Ninja

Күн бұрын

In this video I show how to setup your Google Developer Console to create an OAuth 2.0 consent screen and OAuth2 client id credentials to allow signing in with Google. I then show where to get the official google-auth-library for creating the initializing url and verifying tokens and extracting credentials. After that I show how to setup two Express Routes! One will build the url and pass it back to our React front-end. The other will receive the reply from Google and authenticate the code. I also show how to setup your React UI to ping our backend to retrieve the built URL and ping the GoogleAuth api using the redirect! As a bonus I also show how to use this access token to request the users information from the googleapis for userinfo! I hope that you find this helpful!
Opening Tokens:
• OAuth2 JWT Tokens: How...
There is additional information in here please read thoroughly such as the following
GoogleGSI is probably easier to implement check it out here:
• Login / Signup / SignI...
My channel membership is live check it out here!:
/ @consultingninja
Membership perk video:
• I launched a chatbot w...
SvelteKit OAuth2 Video:
• Sign Up / In with Goog...
PocketBase SvelteKit OAuth2 Video Here:
• OAuth2 using Google, P...
Note Save yourself the headache and do NOT attempt to have a different a separate origin URI from your redirect URI : i.e. do NOT initiate the request from origin URI localhost:5173 and then try to redirect in your backend back to Google. Google will not send the code it will send a Cross Site Request Forgery token that you need an additional package and TONS of work (they rotate the keys), to pull out and verify!
OAuth2Client docs here:
cloud.google.com/nodejs/docs/...
Need help? visit www.consultingninja.tech
Check out my channel @ConsultingNinja for more videos like these.
Requirements when using Google Sign in Docs:
developers.google.com/identit...
Source Code Available Here:
github.com/consultingninja/oA...
Vite Video Here:
• Front-end framework to...
Express Video Here:
• MERN Project: Create &...
00:00 - Intro
01:27 - Google Console Setup
06:00 - ENV Setup in Express
07:32 - Express Setup
20:44 - React Setup
25:52 - Wrap-Up
post release update Googles Documentation is not great and you should play around a bit with opening different pieces of this to see what is inside. As an example: One place in Googles docs said that the field "id_token" only had 4 properties and none of them very useful. However after opening with const ticket = await oAuth2Client.verifyIdToken({idToken: id_token,audience:process.env.CLIENT_ID,}); I found this contained all user information as well. I have found other instances of Googles docs being misleading and or inaccurate. Just a note!

Пікірлер: 66
@ConsultingNinja
@ConsultingNinja Жыл бұрын
Check the description for lots of useful post release information!
@ezeportaep
@ezeportaep 11 ай бұрын
Hello there, how can i send the jwt token to the fortend to storage in the localstorage
@dismasbanda8153
@dismasbanda8153 7 ай бұрын
Your video is very helpful, especially your advice on how to avoid cross-site request forgery. I had to remove Google sign-in from my previous app because I couldn't handle CSRF. Thanks for the video and continue your good work.
@ConsultingNinja
@ConsultingNinja 7 ай бұрын
Glad it helped!
@muhammadnoman6513
@muhammadnoman6513 10 ай бұрын
Thankyou for the video the way you describe make everything simple !
@ConsultingNinja
@ConsultingNinja 10 ай бұрын
Glad it was helpful!
@shadmanfatin777
@shadmanfatin777 5 ай бұрын
Thank you so much bro. You are a genius! May you go a long way insha Allah ♥ (Liked and subscribed)
@ConsultingNinja
@ConsultingNinja 5 ай бұрын
You are very welcome! I am glad this has helped you! Thank you for the like and subscribe!
@shadmanfatin777
@shadmanfatin777 5 ай бұрын
​@@ConsultingNinja❤
@FutureMind323
@FutureMind323 4 ай бұрын
Thank you for the insightful video. I have a query regarding the implementation of complete authentication, this is for both sign-in and sign-up functionalities. What steps should I take after this? Should I opt for JWT implementation, utilize sessions, or consider other options?
@mojgankavehei
@mojgankavehei 7 ай бұрын
great video! Thanks
@ConsultingNinja
@ConsultingNinja 7 ай бұрын
You're welcome!
@LaLaPaPa
@LaLaPaPa Жыл бұрын
Thanks for the video CN 🎉❤
@ConsultingNinja
@ConsultingNinja Жыл бұрын
My pleasure!!
@shainemamigo7133
@shainemamigo7133 Ай бұрын
Thank you so much
@DenysBabych
@DenysBabych 2 ай бұрын
great video, but how i can send a json response with the user on front end if i'm redirecting in oauth get route?
@jinamsancheti2212
@jinamsancheti2212 Ай бұрын
How can i fetch users data after they have logged in, in my react app?
@user-zz4xk5dd3d
@user-zz4xk5dd3d Жыл бұрын
great! how can you validate the token with and generate new token if needed? (if you have refresh token)
@ConsultingNinja
@ConsultingNinja Жыл бұрын
Oauth2client.getAccessToken() getAccessToken(): Promise; Get a non-expired access token, after refreshing if necessary
@Anushkai1
@Anushkai1 7 ай бұрын
Nice Explain
@ConsultingNinja
@ConsultingNinja 7 ай бұрын
Thanks and welcome
@willalexander1595
@willalexander1595 Жыл бұрын
After this, how do we get the user info again on the front end? we can console.log it on the backend, but then we cant do anything with it.
@ConsultingNinja
@ConsultingNinja Жыл бұрын
Hello, It sounds like you are probably more comfortable working in the front-end. If that is the case, then I would suggest you implement the Google GSI method of OAuth as it is mostly done in the front end. Check out the video on this method here: kzfaq.info/get/bejne/qNiDmdapq9eUdKs.html At the end of that video you would simply save whatever user information you want in your backend and the rest is returned to your front-end already (which you can add to if you like). Hope this helps!
@jagdish-main
@jagdish-main 7 ай бұрын
Thanks for the explanation, just had one doubt why we are calling google api to get user data when we already have user data on the access token itself.. can't we just decode the access token it will save some time
@ConsultingNinja
@ConsultingNinja 7 ай бұрын
Yes, you can. Sorry if that wasn't clear. I ended up making another video to try to clarify that here kzfaq.info/get/bejne/ec6FdMaHlazIpoE.html. I was just showing that you can also make use of that API if you needed for testing quickly. You would NOT want to do that in production.
@Edgar-pu1lc
@Edgar-pu1lc 3 ай бұрын
What about github oauth ? Can you make a video about that one ?
@famousfigures
@famousfigures Жыл бұрын
Thanks for the video, but I have a few questions: What is happening at 25:20 once the user signs in? You show a separate screen with all the console logs of token info. The end user (ie, the person who clicked on the button on the frontend) can never see any of that, right? Because those console logs are all happening on the server side. How might we then display some of that information back to the end user on the frontend?
@ConsultingNinja
@ConsultingNinja Жыл бұрын
Hello, It sounds like you are probably more comfortable working in the front-end. If that is the case, then I would suggest you implement the Google GSI method of OAuth as it is mostly done in the front end. Check out the video on this method here: kzfaq.info/get/bejne/qNiDmdapq9eUdKs.html At the end of that video you would simply save whatever user information you want in your backend and the rest is returned to your front-end already (which you can add to if you like). Hope this helps!
@famousfigures
@famousfigures Жыл бұрын
@@ConsultingNinja Thank you! I watched the vid and it helps, but I have a tricky situation and was hoping you could make a recommendation: I have a user admin dashboard app (lets you look up users, see & change their info, etc) that consists of 2 parts: 1) A React SPA frontend for the UI, and 2) a simple Express server backend providing API endpoints that get and update the user data. This is sensitive info, so now we want to secure this app such that only our team members can login & use it. Furthermore, we want to give varying levels of access within the team like admin vs viewer roles. We already use Google workspace for all our logins at work (ie, we have gmail accounts that use our own domain name) and want to continue using those Google logins for this app if possible. So my questions are: What kind of auth flow should we use in this situation? Do we need to store info per user in our server? And critically: How would you recommend we handle the levels of access/roles needed? Ideally I was hoping that we could manage those levels within Google somehow (eg, create Google Groups to represent roles, assign users to those Groups, then our app looks up the user's group somehow during authorization) so that we don't have to keep a separate user DB with access info elsewhere. What do you think?
@ConsultingNinja
@ConsultingNinja Жыл бұрын
Sorry for the delay I didn't see this response. These questions I can't answer without understanding your current architecture. These would all depend on what is already implemented. If I was starting from scratch to implement what you are describing and it is already decided I need my own server I would implement my own users. I would allow OAuth, but I would only use it to sign up and sign in and behind the scenes be routing the info from Google through my server to verify. I would attach role information in my server and NOT in Google. You say "Ideally I was hoping that we could manage those levels within Google", can I ask why? Working with Google is a nightmare. The documentation sucks and is frequently outright wrong, misleading, or missing. This also would create a debugging nightmare since if any of the closed door stuff goes wrong at Google you have no idea what it might be and could potentially spend tons of time trying to figure out a bug that isn't caused by anything in your control. Even in your example this would require you to verify that you write your app with a way to verify the role in your own backend, so just skip that whole step and implement your roles in your backend to begin with. Just my two cents.
@famousfigures
@famousfigures Жыл бұрын
@@ConsultingNinja Thanks for the response, I appreciate it! We're hosting our apps on Azure (but our login uses Google). Looks like we can do the roles through Azure with some extra hoops to jump through, but if not then we will go the local user DB way like you said. Thanks again!
@renjuag8279
@renjuag8279 4 ай бұрын
Thanks for the video. Once the authentication is successful, google redirects the flow back to the application with the 'signin-google' route.But im getting 500 Internal Server error and the request fails every time.
@dhanujayayapabandara384
@dhanujayayapabandara384 2 ай бұрын
Did you do successfully this task
@32srajanr39
@32srajanr39 4 ай бұрын
It works on localhost, but fails in live site, i have added live site link also live site backend route to credentials, i am getting invalid_grant error when i try from live site after the user selects the account
@ConsultingNinja
@ConsultingNinja 4 ай бұрын
This is most likely because there are pretty tight restrictions to using this in "testing" mode You have to publish your app in order to use in hosted domains. Go to my website : www.consultingninja.tech/ and use the contact form to send me a message with your email. I will send some screenshots to guide you. Sorry for the delay I didn't see this.
@basithp9467
@basithp9467 5 ай бұрын
Please do a video on Google Sign in using Flutter and NodeJs
@ConsultingNinja
@ConsultingNinja 5 ай бұрын
I can add that one to the list.
@Alchemist_dream
@Alchemist_dream 3 ай бұрын
i got those info , but since im in a redirect url , how am i suppose to set cookie inside browser , i got stuck there , i cannot send those info or token in front , i saved it in data base , but again i don't have a unique identifier to find that user , i just stuck with those info in redirect url , two days and i haven't find a solution ,
@alenaju1847
@alenaju1847 3 ай бұрын
send your github url
@user-yn4qr7hu9r
@user-yn4qr7hu9r 4 ай бұрын
hey i did the google login just like you explained and i am getting the most part except for the users actual data in the final reaponse in the oauth.js file do you have any idea about why that is happening this is the data object i recieved to my /oauth route data: { error: 'invalid_request', error_description: 'Invalid Credentials' } if anyone knows the solution please help
@user-yn4qr7hu9r
@user-yn4qr7hu9r 4 ай бұрын
i also did not get a refresh token as well
@ConsultingNinja
@ConsultingNinja 4 ай бұрын
Check your email
@icalculi
@icalculi 6 ай бұрын
are signup and signin the same for oauth2.0? also, what do i need to save in the database to 'identify' and or distinguish the user?
@ConsultingNinja
@ConsultingNinja 6 ай бұрын
Yes they are the same. oauth2 is just a standard authentication (who the user is) implementation. That can be used for both signing in and signing up. I think this other video will help you. Check this out. kzfaq.info/get/bejne/ec6FdMaHlazIpoE.html As to the last question, what I do is I take the information that comes back from the oauth2 response and create a user in my database with all (or most) of the information from payload (explanation in that video link). I add one field to my users ; which Is an application specific id (specific to MY application). Technically the never changing value (for Google) is the sub property, short for subject. That is the id in Google that never changes and is account specific. You could just use that if you want, but I like to always have two completely unique values in my applications that should never change and thus two ways to find a user. Most all of the other information is possible to be changed, including email address. Hence why Google always has users setup multiple email addresses for account recovery. But that is a story for another day. I hope that this helps! Mitch Migala (CN)
@icalculi
@icalculi 6 ай бұрын
@@ConsultingNinja thanks, very helpful cheers!
@diggman33
@diggman33 6 ай бұрын
hmmmm.... I am getting a 404 after selecting a valid google account from the 'Choose an account' page... reviewed code in github and everything matches, so Im not sure why this is happening
@ConsultingNinja
@ConsultingNinja 6 ай бұрын
This happens when your redirect url in google console is redirecting the request to the wrong spot. Where is your route being hosted? That is where the redirect url should be pointing. Double check that in your Google developer console. And make sure it matches your actual route.
@ashwanthdurairaj7148
@ashwanthdurairaj7148 Жыл бұрын
yo, how to access email address from OAuth function
@ConsultingNinja
@ConsultingNinja Жыл бұрын
add this to the example console.log('credentials',user); const ticket = await oAuth2Client.verifyIdToken({idToken:user.id_token,audience:process.env.CLIENT_ID,}); console.log('ticket',ticket); There is extra information inside of [ticket], this will also tell you if the email has been verified. BUT remember that the email CANNOT be saved as the user! If a person has created a Google account with another email they can change the email to another one then their account will be broken in your app.
@themacosguy
@themacosguy 11 ай бұрын
@@ConsultingNinja But this code doesnt give us an email address. How do we decode the output give the email address.
@ConsultingNinja
@ConsultingNinja 10 ай бұрын
Using the above function const ticket = await oAuth2Client.verifyIdToken({idToken:user.id_token,audience:process.env.CLIENT_ID,}); console.log('ticket',ticket); That will in fact give you the email address as well as other information.
@RitikRaj-we2sc
@RitikRaj-we2sc 3 ай бұрын
Hey I have implemented google auth using passportjs. Now, locally it's working fine, but after I deployed it to vercel, then ven though consent screen is shown, I am not getting back the cookie, and therefore use is not getting authenticated. Please tell me what could I be doing wrong. I am stuck on this for more than two days.
@ismaelpaul367
@ismaelpaul367 3 ай бұрын
If you are hosting client and server with different domains, the cookies won't work as you can't exchange cookies cross domain. I am having the same problem.
@RitikRaj-we2sc
@RitikRaj-we2sc 3 ай бұрын
@@ismaelpaul367 hey I got the solution. You just need to add this line to your code to make it work. app.enable("trust proxy")
@shivamarora7422
@shivamarora7422 7 ай бұрын
Having the problem after logging the details I am unable to redirect to the frontend homepage it gets stuck on Google Sign In page only
@ConsultingNinja
@ConsultingNinja 7 ай бұрын
What does it say in the console?
@shainemamigo7133
@shainemamigo7133 Ай бұрын
Did you fix this issue bro, i got rhe same problem
@swagz6440
@swagz6440 5 ай бұрын
I am being returned the error: "{ error: 'invalid_request', error_description: 'Invalid Credentials' }" even though i console.logged the user being requested and i got the access token, refresh token and everything
@ConsultingNinja
@ConsultingNinja 5 ай бұрын
Try the following: Go to console.developers.google.com/ Select your project. Click 'APIs & auth' Make sure your scope includes "email" and "profile" Wait 10 minutes.
@swagz6440
@swagz6440 5 ай бұрын
@@ConsultingNinjaThank you however I fixed it in the url I added an = after the ?access_token
@user-xy5km9uq8l
@user-xy5km9uq8l 7 ай бұрын
Normal
@Joaoboscodelima.Boscodelima.
@Joaoboscodelima.Boscodelima. 10 ай бұрын
Emuitocompricado.
@ConsultingNinja
@ConsultingNinja 10 ай бұрын
There is a more simplified way to implement oauth in your app using Google GSI, you can see that here: kzfaq.info/get/bejne/qNiDmdapq9eUdKs.html
OAuth2 JWT Tokens: How to Open Tokens / What is inside
9:34
Consulting Ninja
Рет қаралды 1,5 М.
Google OAuth 2.0 With NodeJS (No Passport or googleapis)
57:18
TomDoesTech
Рет қаралды 93 М.
Inside Out 2: Who is the strongest? Joy vs Envy vs Anger #shorts #animation
00:22
Задержи дыхание дольше всех!
00:42
Аришнев
Рет қаралды 3,8 МЛН
Login / Signup / SignIn with Google GSI | OAuth2.0
20:34
Consulting Ninja
Рет қаралды 2,8 М.
NodeJS & Express - Google OAuth2 using PassportJS
20:33
Kris Foster
Рет қаралды 98 М.
Adding Google Authentication with express node
12:43
Google Identity Services Login with React (2023 React Google Login)
19:50
My opinion on Angular 18 & React 19
9:47
Maximilian Schwarzmüller
Рет қаралды 53 М.
Auth0 authentication in Reactjs using OAuth2
48:19
Mafia Codes
Рет қаралды 69 М.
JavaScript Visualized - Event Loop, Web APIs, (Micro)task Queue
12:35
OAuth 2.0 explained with examples
10:03
ByteMonk
Рет қаралды 116 М.
Vision Pro наконец-то доработали! Но не Apple!
0:40
ÉЖИ АКСЁНОВ
Рет қаралды 525 М.
$1 vs $100,000 Slow Motion Camera!
0:44
Hafu Go
Рет қаралды 29 МЛН
Klavye İle Trafik Işığını Yönetmek #shorts
0:18
Osman Kabadayı
Рет қаралды 9 МЛН
Xiaomi SU-7 Max 2024 - Самый быстрый мобильник
32:11
Клубный сервис
Рет қаралды 553 М.