Google OAuth 2.0 With NodeJS (No Passport or googleapis)
Вставка
- Опубліковано 5 вер 2024
- Repository: github.com/Tom...
📚 Concepts & technologies covered
- OAuth 2
- JWT
- Authentication & authorization
- TypeScript
- Node.js
- Google OAuth 2.0
🌎 Follow me here:
Discord: / discord
Twitter: / tomdoes_tech
Facebook: / tomdoestech
Instagram: / tomdoestech
TikTok: / tomdoes_tech
☕ Buy me a coffee: www.buymeacoff...
Just remarkable way of explaining OAuth 2.0; that diagram has solved all my 'how it works' doubts, and also didn't know that some services do not verify e-mail addresses... 👌
looks good but one feedback is to not have music in the bg its pretty distracting
This was great, just what I wanted to see, raw implementation, to really understand the work flow
Thank you, sir!😇
Wow, dude, it's incredibly beneficial in enhancing my comprehension of the process.
A quick advice… when teaching some modules… please try to do it in a single code… dont jump around… it is easier for the learner to understand
If anyone is facing the error - An error occured while saving your app - According to Google's new policy you cannot include the keyword Google in your app name so try removing that
Beautifully explained, thank you Tom!
Does anybody know where to find these URLs? I can't seem to find them on Google or the documentations
Great tutorial! I really like the fact we built most of the implementation from scratch.
There's one part that I am really confused about right now and cannot seem to find the answer to elsewhere.
Once I have created the custom user document on my backend as well as the access/refresh tokens, how do I then send this data to my frontend and put it in my Redux store?
An answer to this would be a massive help to me right now. Thank you.
You can send the access and refresh in the response of the auth request.. and then the front will store it in redux for further requests
Finally found what I was looking for 🙌
First off, great video, watched it from start to finish but why stress? why not just use passport?
You can use passport if you like, but this video is meant to teach you how Google OAuth works, not how some library works
Amazing tutorial, it's been immensely helpful to me. One clarification:
In the final 8 minutes, from "Create session" onward, you're just manually creating a JWT based off the user's information *pulled from the database* right? My big question is, are you using anything retrieved from Google's API in this manual JWT process, or are you just grabbing user info you have stored in Mongo, making a JWT, and sending it forward as cookies?
Basically, the id_token and auth_token from Google are ONLY to access Google information, and have nothing to do with the session state *of your actual application*, right?
Again, thanks for an incredible tutorial!
this is the correct and commonly followed approach after getting session validated from google while login we pass our server generated jwt which can be received into every protected routes onwards
Finally ! you are really good thank you Excellent explanation
That means from frontend will have a getUser function, base on accessToken and refresh token
Very fine work man. Keep it up ;)
Hey Tom, amazing video thank you!
I am implementing OAuth in an API with Fastify, but there are two things I’m still confused on.
Firstly, do we need to check with google at some point that the users OAuth credentials are still valid? For example if they revoke access through their google account? Because with this setup they would still remain logged in with the app as after login authorisation is done with our JWTs not Google’s.
Do you also have to revoke the user’s google OAuth tokens if they delete their account? I can’t seem to find a consensus on if this is necessary
Thank you again! 😊
I have the same question. Let me know if you find the answer to this question.
Nice, but too be an small repo, tracking the call between modules is a little complex.
Hi, can I ask how a user information is stored & retrieved from the database using oauth2.0? Thank you
Amazing content Tom! Thanks!
Very thanks but have a problem with token it set in localhost but not in production have express in backend and nextjs in frontend both hosted on vercel with custom domain i put res.cookie httponly:false secure true but token is not set i need help pls😢
Thank you so much! This was helpful
But, if you have the redirect url to your client, wouldn't the client then have to intervene in the oauth flow? Timecode 9:50
Congrats for 2k subscribers. Do you plan a discord channel for your subscribers maybe?
Thank you :) To be honest, I haven't thought about it. What would be the benefits of starting a discord?
For you: Community building - > Range on influence = $$. Notificationa for the followers that there is a new Video - > higher click rate in the first hour - > better ranking - > more $$ from UA-cam. Get easier partnership, if they see you you have a good amount of subscriber and acrive users on discord - > $$. Find mistakes like the documentDefinition faster. More satisfying for the user, will come back with a higher chance -> more subscribers -> $$. And of course there is much more you can do with high range of influence.
For us: E.g. Discuss mistakes in the video, help each other out
Hey Tarik, I created a Discord server :) discord.gg/4ae2Esm6P7
Thanks so much for the suggestion!
Thanks, you are very helpful
Just what I needed. Thanks.
How can i use jwt instead of cookie, and send jwt and redirect to /home route??
Hi tom nice tutorial, can you please share the docs how to implement this google Oauth from google page?
can i build facebook login the same way? amy major difference in consent screen url construction?
The principals of OAuth are the same but there are differences in getting the credentials and consent screens.
@@TomDoesTech this is amazing! demistifies all the magic for us who had been using packages all the time. thank you.
@@TomDoesTech if you ever decide to make something similar about facebook auth, I'll sell you my soul with the cheapest price available on amazon.
Great tutorial!
Thanks for the useful video!
I have a question, does this code is the authorization code from initCodeClient() ?
whoo i finally got the right video ❤
useful tutorial!
Hello, when I install a node.js application, I write "init" to an empty file and install it and create app.js myself. Is there an easier way or a ready way to do this??
Thanks. It was awesome!
extremely benificial man
Great tutorial! I would like to ask, what if a new user wants to login? Instead of findAndUpdate I have to create a new user right?
nevermind, I just knew what upsert means
Would storing the sessions in Redis instead of a database be a better approach? Or is that something you should only worry about when your app is scaling, on a needs basis. I take it storing the sessions in a database would be fine for little side projects?
Redis would be a great place to store that data. However, I would avoid adding new tech to a project until it is required to solve a problem. I'd guess that most systems wouldn't have a problem storing that data in a database for quiet a while.
Is it possible to perform this:
I would like to have calendars available for reservations. A 3rd person will receive a card in the front end with an available grid to pick to reserve time. But this person won't do a consent or anything, will just select a time.
Then at the backend it will hit Google Calendar API of the resource(aka: random professional sharing services) to get a turn/booking reservation. The availability will be restricted in the frontend, and also will be consulted the time slots available between that gap defined.
The doubt i have is that somehow or at least once a week the resource must give consent, how would you do it? Will it have to be done manually? Or can the backend do it on behalf of the resource?
hey with localhost I am getting invalid request error (google says on localhost i can't use auth2.0 anymore) . what should i do ?
Quick question, don't you have problems upserting the user because the password field is required?
Either make the password field not required, or insert a random string as the password
Where to find the rest api endpoints for oauth2.0 ?
Is there any postman collection?
Thank you
what is the point of storing user data on database after oauth? does that mean users will be able to login using google oauth credentials? if so where is the password being stored?
If you don't need a user's table, don't have one. But it's rare you won't need it
thank you!!!
why did you stop making video sir ?? We want your comeback
I haven't stopped, just been very busy
when I use the axios post it returns: {error: 'invalid_grant', error_description: 'Bad Request' }
AxiosError: Request failed with status code 400.
Still stucking here and can not have the access_token like your video
Hi Thomas
I too was stuck here, but I got around it using this:
const { google } = require('googleapis');
const oauth2Client = new google.auth.OAuth2(clientId, clientSecret, redirectUri);
const { tokens } = await oauth2Client.getToken(code);
const { access_token, id_token } = tokens;
I hope this helps.
Amazing video code!
Bro, this tutorial was awesome!! Great for people that wanted to learn things the "hard" way and yet, you made it quite easy to execute. Also google oAuth is quite well documented. I'm using this for the UA-cam api scopes and it worked simply by replacing scopes
great thanks 👌
I get redirect mismatch every now and then. I just edit the client and it works . After 30 minutes. It fails again
Hey!
I saw that you answered on this question a couple of times but something I can't figure out is the following. You said that instead of setting cookies we could return the access and refresh token in the a JSON body. But the implementation shown in this tutorial is using a redirect from Google to the back-end via a GET request which means we can't send JSON data back to the React application.
The only idea I had was that after a successful login on google we redirect the user back to the react app and than check if the URL contains a "code" query parameter and than do the request to the back-end, but that seems like a unnecessary step. Do you have an suggestion on how to approach this problem?
this is commonly done in the way you describe. for example you could have an access token and refresh token for your own authentication also.
Awesome Tutorial as always +++++++++++++++++ Thank you 🙂
Hi where is the video to create session and cookies
Can we surpass the consent screen?
I do not want to show that in my application.
I want to work internally.
No the user has to give consent for your application to access their Google data
Hey! This tutorial helped a lot and made the Google OAuth flow extremely clear!
I had a question, instead of setting cookies and redirecting the user at the end, is there any way that we send the jwt access token so that we can set it in local storage in the client side?
Yeah of course, just put in the response body
Your coud just use this: ua-cam.com/video/5WehZTrgG8o/v-deo.html
Even simpler: ua-cam.com/video/5WehZTrgG8o/v-deo.html
i like your terminal
It's just the VsCode terminal
hi Tom, thank you for the tutorial. How can I integrate the UI with Angular
I am good at react but I can't make good looking Ui components, TBH I am not confident at my css skills. Any suggestions on how to improve myself in css?
TailwindCSS was a lifesaver for me.
@@reknine thanks! I'm currently learning chakra ui.. I'll try tailwind css as well.
I'd recommend Material UI as it's more widely used in companies
how to impliment in react native?
Is this in continuation with first video of playlist or a separate video?
Yeah, it's a continuation
What about sign up with google?😢
@@JoeElmasry. Isn't that what's in this video?
Isn't this method vulnerable to csrf attacks? You should be using a csrf token in the oauth state.
So the same method but include a state param?
@@TomDoesTech Basically you create a random string at the beginning of the process when you hit your api/sessions/oauth/google endpoint and you would save that string locally (like in a session) and pass that string with as the state query param. Then the oauth provider will pass that string back to you unchanged as the state query param in your callback and you can compare the strings. This way you can make sure that the request is coming from the actual user and not an attacker. There are a many articles written about this but the auth0 team has a pretty short and to the point article if you google "csrf attacks in oauth".
@@_stevek Yeah, I know what a state parameter is. But that's the same method here with an extra step
@@TomDoesTech It's the same method you are using except when you initialize the authorization process you should create a token ( a unique string ) and save it to a session/cookie and the pass it with the state param to the oauth provider. Then when they redirect back to your site to your callback route you can grab that token from the state and from your session/cookie and compare them to make sure that the user initialized the authorization on your site and isn't an attacker.
How bout those of us that aren't using NextJS???
You learn the concept and adapt it to whatever you are using
@@TomDoesTech thanks for the response.
I asked because I was getting stuck with errors.. especially with the yarn dev
But I'll just look it up online
Thanks for the tutorial ✨
@@TomDoesTech the problem still persists. I guess it's cuz I'm not using NextJS. Cuz all my other projects work just fine.
The script in the file literally says:
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
}
the missing video
I wanted to do Google sign without passport, but you have cloned the git repo which you have done in previous video. In the pre video, you cloned something you made before that, so to start this video I have to understand what you did in other videos and repos first which is unfavorable. Please start from scratch in new videos or at least explain what is in the cloned repo already.
This video is part of a series
Great Content, but most practical cases api and frontend domain are not same so cookies cannot be set from backend
In most cases, the host is the same. Even if the domain is different, you can still set cookies. Set the domain property to the client's domain.
If what you said was true, most of the internet would be broken.
@@TomDoesTech
Setting cookies for another domain is not possible. If you want to pass data to another domain, you can encode this into the url. You can't, at least not directly. That would be a nasty security risk. ?
@@nepalcodetv6298 you can send the tokens in the response and set them client-side, like Google Analytics does.
But in most cases your API is going to be on the same host. So if your website is example.com and your API is at api.example.com, set the cookie domain to *.example.com
@@nepalcodetv6298 I tested it locally with Ngrok and you're right. You can't set the cookie from a different domain.
However, I don't think this would be most cases. I think in most cases the API will be on a subdomain and it's possible if the hosts are the same.
if the API isn't on a sub domain, you could use a proxy, like Nginx, set the cookies client-side, or even just use local storage.
@@TomDoesTech setting cookie for a different domain would be a security problem
thank you