Registration and Login with JWT Authentication Tutorial - NodeJS Tutorial

Поделиться
HTML-код
  • Опубликовано: 23 ноя 2024

Комментарии • 138

  • @julietswanson8458
    @julietswanson8458 3 года назад +7

    Your videos are amazing!! This tutorial is the perfect balance of explanation vs. instruction for a beginner-to-intermediate JS learner. Thank you so much for making these concepts super accessible and easy to follow. Subscribed!

  • @imasharc
    @imasharc Год назад +1

    Your explanation & tutorial helped me *finally* understand how to implement JWT! Amazing job

  • @nxdeforest
    @nxdeforest 3 года назад +7

    This is a really great intro to JWT. definitely helped me understand how to implement for my own project. Thanks!

  • @nisargshah6266
    @nisargshah6266 Год назад +2

    hands down the best tutor to leaarn from

  • @lucylu184
    @lucylu184 3 года назад +4

    your channel is a hidden gem! I'm so glad I found it

  • @oussemabouyahia474
    @oussemabouyahia474 Год назад

    this is really the best explanation , please do we can create more than one token , for example a token for admin to access some routes and another token for simple users

  • @muhammadhammad1700
    @muhammadhammad1700 3 года назад +1

    great explanation.
    but I want to integrate this with my react js frontend, I am confused about how to display the errors in the frontend.

  • @aliraihannashrullah6048
    @aliraihannashrullah6048 10 месяцев назад

    Your video is really beginner friendly, thank you so much for your help !!

  • @alizafar2187
    @alizafar2187 Год назад +1

    Thank you sooo sooo sooooooo much . This is the only video that helped me

  • @jeromeborga2198
    @jeromeborga2198 2 года назад

    You are a life saver ! Do you have any video on the same stuff on front end ? How to set it on local storage ?

  • @BenLamptey
    @BenLamptey 2 года назад +3

    absolutely beautiful video. wow, thank you! Hope to see content from you on the authorisation you mentioned. Also any chance we could get a video that continues from this where we can pull content just for that particular user. for e.g. they can see a list of all articles they created on the site

  • @digvijayyamagekar4300
    @digvijayyamagekar4300 2 года назад +1

    What is the most secure way to store a JWT token on the client side ?
    local storage, session storage, cookies all are vulnerable to XSS or CSRF attacks.

  • @rafj9883
    @rafj9883 3 года назад +1

    Caraca, tu tá lendo pensamento...tava pesquisando isso ontem!!! Valeu pelo vídeo.

  • @sakatagintoki4211
    @sakatagintoki4211 2 года назад +1

    I like the way you explain. It's clear and easy to understand.subscribed!

  • @jorgedavalos5663
    @jorgedavalos5663 2 года назад

    your tutorials are the easiest to follow, thanks!

  • @usmanmughal5916
    @usmanmughal5916 3 года назад +4

    This is my 100th time watching JWT on RUclips :) OMG nice video.

  • @CuriousAnonDev
    @CuriousAnonDev 2 года назад

    most detailed video on this topic!
    thanks, i learned a lot

  • @joseaquiler
    @joseaquiler 3 года назад

    your channel made me discover the gem of gems, sequelize...

  • @melissatermin5551
    @melissatermin5551 2 года назад +1

    I think it will be benefical to make the same video with PERN stack but combining two table that user can only his/her data instead of seeing everything

  • @felnoga
    @felnoga 3 года назад

    After if(!match) you should return the response: return res.status(400).json({error....}). This returns from the function and does not continue the execution of the next lines. This is why you received 'LOGGED IN' even with the wrong password. You should exit the function with return.

  • @SixtyNeptune
    @SixtyNeptune 3 года назад +4

    man you should teach us how to redirect after registeration in react and express

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +4

      I have videos on how to use React Router Dom! You can use the component! I should make more videos on this soon!

    • @mastercode7851
      @mastercode7851 3 года назад +1

      @@PedroTechnologies yes please i am waiting for that and thanks :)

  • @tusharnain6652
    @tusharnain6652 2 года назад

    please make a video on how to implement "Log out from all other devices."

  • @TegarPenemuan
    @TegarPenemuan Год назад

    What a video. I understand it easily. Thank you very much. Permission to ask, because I'm still a beginner. I don't know how to make logout feature?? if there is your video related to this. please send the video link.

  • @peachytimeu
    @peachytimeu 3 года назад

    Thank you so much! It helped me a lot as a self-taught. I'm crying finally I can do it now T^T

  • @learnmakeit9315
    @learnmakeit9315 Год назад

    Thank you for this video. I have an error. const accessToken = req.cookies["access-token"]; It gives me "User not Authenticated! because accessToken is undefined. I checked it with console.log. It seems like it runs validateToken twice, and the first time, it gets the token, but for the second time, it gets undefined. What can be the problem? I have looked for the solution for a long time, but couldn't find it.

  • @__shubhamtiwari
    @__shubhamtiwari 11 месяцев назад +1

    Waah! Kya baat hai pedro dost ❤

  • @faris.abuali
    @faris.abuali 2 года назад +1

    Thanks Pedro! 👏
    Simple and informative

  • @ishimwesage7991
    @ishimwesage7991 2 года назад

    Can please continue on this video and connect with react for font-end Thank you so much.

  • @synguyenvan9439
    @synguyenvan9439 Год назад

    thank u guy. But i have a question about refresh Token. When Token is expried, how can i refesh. Please

  • @__shubhamtiwari
    @__shubhamtiwari 11 месяцев назад +1

    Waah mast video hai ❤

  • @ishimwesage7991
    @ishimwesage7991 2 года назад

    Can please continue on this video and connect with react for font-end Thank you so much. please i beg pedro.

  • @joseisraeldiazzapata5179
    @joseisraeldiazzapata5179 3 года назад +1

    Awesome video Pedro thank so much :3. With the cookie created or the jwt, is it possible send it to the frontend to use the data of the user for example in a welcome message or the classic button on the right corner(sign-in / sign-out) ?

    • @PedroTechnologies
      @PedroTechnologies  3 года назад

      Yeah, after you make the request in the frontend you can just check to set a global states to be logged in!

  • @fuelledbycoffeee
    @fuelledbycoffeee 3 года назад +1

    Should I use this video as reference or your other video titled "Authentication With JWT Tutorial - React, NodeJS | How To"?

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +1

      I feel like this one is more complete!

    • @fuelledbycoffeee
      @fuelledbycoffeee 3 года назад

      @@PedroTechnologies thank you so much for the response! Have a good day!

    • @fuelledbycoffeee
      @fuelledbycoffeee 3 года назад

      stucked in "Please install mysql2 package manually" issue. might go back and use your old auth tutorial :(

  • @pedrodelnero6557
    @pedrodelnero6557 3 года назад +1

    Really enjoyed the video, clear and to the point. Wanted to ask you about cookies, req.cookie sets the cookie for localhost:5000 (backend), how to set the cookie for the frontend? Like localhost:3000

    • @pedrodelnero6557
      @pedrodelnero6557 3 года назад +1

      Edit: You have backend as localhost:3001. But how to send cookie to diff url?

    • @PedroTechnologies
      @PedroTechnologies  3 года назад

      The cookie is set to the frontend! When you write res.cookie() it sets to the client side!

    • @pedrodelnero6557
      @pedrodelnero6557 3 года назад

      ​@@PedroTechnologies Figured it out. I use axios in the front end so needed to add "withCredentials = true". I believe it works like cors does for the backend.

  • @gustavomontirocha
    @gustavomontirocha 3 года назад +1

    Amazing!! Could you go ahead and make requests that belongs only for the authenticated user? Another nice tip is showing how to do expiration and refresh with frontend :)

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +2

      Thank you! I plan on making a video on refresh tokens and maybe include a logout functionality in it as well! With what we wrote in the video you can make requests that only belong to certain users, but that is authorization and not authentication.

  • @mbfreitas0
    @mbfreitas0 3 года назад +2

    Pedro as suas aulas são ótimas !!! Seria possível me ajudar em uma dúvida? após o login o usuário precisa ser direcionado para uma página principal, por exemplo... no seu código desta aula o roteamento seria feito no index.js ? Dentro da função app.post("/login", async (req, res) => { ... ?

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +1

      Boa Marcelo, obrigado! Após o login vc pode redirecionar dependendo de como seu frontend é. Você esta usando react? Ou somente html?

    • @mbfreitas0
      @mbfreitas0 3 года назад +1

      @@PedroTechnologies Eu estou estudando o seu código mesmo, deste vídeo. Imaginei que após o login o usuário seria direcionado automaticamente para uma página principal, por exemplo. Eu estou usando o ReactJS

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +1

      @@mbfreitas0 Apos o logi, vc tem que redirecionar através do React. Eu fiz um video falando sobre os diferentes metodos que vc pode usar pra redirecionar: ruclips.net/video/tiAlSpyWIDs/видео.html

    • @mbfreitas0
      @mbfreitas0 3 года назад

      Legal Pedro vou assistir agora !!! Muito Obrigado pela Atenção \0/ ...Estou aprendendo muito com suas aulas !!! Valeu !!!

  • @siddheshmhatre2389
    @siddheshmhatre2389 3 года назад +1

    Nice content 🤝💥But what about to stop the user after logged in not to come back to login/register page?Like how to protect that routes after loggedin?

    • @PedroTechnologies
      @PedroTechnologies  3 года назад

      Thank you! I've been showing how to do this in my new series about full stack development!

  • @romimaximus
    @romimaximus 3 года назад +1

    Really well explained !! thankx Pedro 👍

  • @gomathym97
    @gomathym97 Год назад

    Please do bulk email sending tool by using MERN stack

  • @sonamohialdin3376
    @sonamohialdin3376 2 года назад +2

    Amazing tutorial

  • @FrostGhost
    @FrostGhost 3 года назад +3

    Hey Pedro, thanks for making this video - it was really helpful! I successfully implemented this in the back-end of a project I'm currently working on. However, in the front-end (I'm using React), where should I store whether a login is successful or not? I know in previous videos you created a state called loginStatus and set it to true if the login was successful, but this doesn't seem secure to me as a user could just change that state to true! What is the most secure way to do this? Looking forward to your reply! Thanks bro!

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +2

      Hey, there are many ways of doing this! You can save it in your sessionStorage, in a global state, and many different places. This won't be insecure because even if they change the state to logged in (which wouldn't work because you cant change a state through the browsers js), you should be validating every api request through the tokens!

    • @FrostGhost
      @FrostGhost 3 года назад

      @@PedroTechnologies Hey, thanks for the prompt reply. So I would set a global state in sessionStorage to true if they are logged in. Then would check the value of the global state before rendering the new page. If it is set to true, then render the new page. If I did it this way, then someone could still set their sessionStorage state to true and bypass the api request and end up rendering the new page? I know you said that changing a state through browser js isn't possible, but if someone managed to somehow set it true, wouldn't the new page end up rendering? Thanks so much bro!

    • @FrostGhost
      @FrostGhost 3 года назад +1

      @@PedroTechnologies Maybe a video on this might be a good idea! I couldn't find anything online which explained how to render a new page in React once a user has been authenticated (using JWT and a HTTP cookie)... Thanks bro!

    • @edoardopavan6128
      @edoardopavan6128 2 года назад

      @@FrostGhost were you able to find any online resources?

    • @FrostGhost
      @FrostGhost 2 года назад

      @@edoardopavan6128 Hey, I realised much later after doing many projects using React that Pedro's original answer to my question is correct. The state cannot be easily changed and even if it is, any request to the back-end should have authentication (using sessions). If the authentication fails, the request will fail meaning the front-end won't display the data. So the way shown in this video is secure, providing your backend is secure..

  • @skl949
    @skl949 2 года назад

    i love your videos so much bro!! thanks! also pleaase do refresh tokens as well

  • @anishbishnoi29xD
    @anishbishnoi29xD 3 года назад +1

    PROTECTED ROUTE ? Login user cant access Signup page. until logout.
    and login user cannot login again .
    and store token Database and validate session

    • @PedroTechnologies
      @PedroTechnologies  3 года назад

      Validating with sessions is a different type of authentication. In this case you can indeed use a protected route which is defined in the frontend. You can make a request to your server to check if you have a valid token in your http only cookie, then if so, you set some global state to allow you to login.

  • @Praxis_by_tanay_pingalkar
    @Praxis_by_tanay_pingalkar 3 года назад +2

    How to add Google authentication ? Can you make a video on it

  • @monarchgam3r
    @monarchgam3r 2 года назад

    Awesome video, thanks man... Can you do the front-end implementation of this same auth flow?
    How will you use httpOnly cookies on the front-end.. I heard they only work on same domain, which isn't possible in development since server and frontend are on different ports
    What's your solution for this

  • @LuuCasS681
    @LuuCasS681 6 месяцев назад

    Please, can you help me with a question ? when the user successfully logs in, do we usually handle the user redirection to a new page on the server or on the client side ?

    • @bereketg5609
      @bereketg5609 5 месяцев назад

      On the front using use navigation from react router from library

  • @k303k
    @k303k Год назад

    Thanks for the video pedro!!!

  • @ThColinPereira
    @ThColinPereira 3 года назад

    this video is banging! thanks pedro

  • @samiragalarov5623
    @samiragalarov5623 3 года назад +1

    hi 32:00 i did same thing with react and node Js .I cant see any cookie on my client side .Please help me

    • @jiwachhetri4165
      @jiwachhetri4165 2 года назад

      hi, did you mange to figure out how to login / verify from client

  • @dcpclassroom1999
    @dcpclassroom1999 Год назад

    Thank you so much. It is really helpful

  • @louislecouturier
    @louislecouturier 3 года назад +1

    Thanks a lot pedro !!! How can I implement this on my frontend ?

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +1

      I have a video on it: ruclips.net/video/KgXT63wPMPc/видео.html

    • @louislecouturier
      @louislecouturier 3 года назад

      @@PedroTechnologies thanks ! but how can you retrieve user data and display it in your page ?

  • @kousiclattala7380
    @kousiclattala7380 3 года назад +1

    in validateToken method i'm unable to get the accessToken, it is saying "cannot read property token"

    • @PedroTechnologies
      @PedroTechnologies  3 года назад

      Interesting, this might be a typo. Are you using typescript or js? Can you paste your code here for the token?

    • @kousiclattala7380
      @kousiclattala7380 3 года назад

      @@PedroTechnologies Thank you Pedro for your response, I have rectified my error, I got the error because I'm sending a request to the backend without including a token in the headers. I have changed a little bit code from yours, you used "req.cookies["token']" to get the token from front-end, I used "req.headers["cookie"]", this is because I'm sending it as "cookie : ", through the headers, from the front-end.

  • @erklyn
    @erklyn 3 года назад

    Working quite well but I do have a question when I make the post request from my frontend(reactjs) the cookie won't automaticly go in the application of my browser i am using chrome and it's really frustrating , I can see my cookie in the request's cookie and I don't know how to get that cookie. If you could help with that I would be so gratefull

    • @priyanshugupta9011
      @priyanshugupta9011 8 месяцев назад

      hello , i am encountering the same error when trying to connect with frontend
      if you got the solution for it can you please comment it down

  • @swapnilmane1599
    @swapnilmane1599 3 года назад +1

    Thanks...it is the very simple jwt auth I have Ever watched... Superb...🔥♥️. Bt how to get current logged in user's details...???

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +1

      Thank you :) Well, you can store the access token in somewhere accessible when someone logs in (Ex. cookies, session/local storage (although not recommended)) and just verify them to get the information!

    • @swapnilmane1599
      @swapnilmane1599 3 года назад

      @@PedroTechnologies Yes...I did...I verified n got back the data which I stored into the jwt... Thank You So Much for this tutorial...This cleared my mind about jwt auth... seriously...thanks a lot... This Tutorial is quite helpful...😊

    • @swapnilmane1599
      @swapnilmane1599 3 года назад

      @@PedroTechnologies And make a video or videos on Admin Bro... please...😊...They way you teach, it clears every doubt...Thanks Again...Jwt video helped me out from JWT AUTH infinite loop of not understanding of the concept...😂😂

  • @shorelinefilms9661
    @shorelinefilms9661 2 года назад

    Hey Pedro, whenever I add in the wrong password in the login it crashes my server. Is there a way to make nodemon not crash.

  • @kushagratibrewal7214
    @kushagratibrewal7214 3 года назад +1

    This Channel Shares so much Good Content and it was hidden from me a long time . thats sad but now i got this i am sure i will able to be into web dev and make proper apps . Thank You So Much Pedro Thanks Again!
    Also Can u share the Extensions you use for VS Code for Website Development

  • @majdshatti5677
    @majdshatti5677 3 года назад +1

    it's a really nice video but i am facing a problem. when i'm using postman i'm getting the thing done but when i use react post request i'm getting req.cookies as a [Object: null prototype] {} do u have any idea why :(

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +1

      Interesting, can you paste ur code here so i can take a look?

    • @majdshatti5677
      @majdshatti5677 3 года назад

      @@PedroTechnologies /// React Axios
      handleSubmit = async (event) => {
      event.preventDefault();
      const formData = new FormData();
      formData.append('username', this.state.username);
      formData.append('password', this.state.password);
      const res = await axios.post('localhost:3001/api/login', formData).then( response => {
      this.setState({resMessage: response.data.message});
      this.setState({resStatus: response.data.status});
      if(response.data.status === 'good'){
      alert(response.data.status);
      }
      else{
      alert(response.data.status);
      }
      });
      }
      /********** Express index.js ***********/
      const express = require('express');
      const app = express();
      // Cookie Parser
      const cookieParser = require('cookie-parser')
      // Cors
      const cors = require('cors');
      // Body Parser
      const bodyParser = require('body-parser');
      app.use(express.json());
      app.use(cors());
      app.use(bodyParser.urlencoded({extended: true}));
      app.use(cookieParser());
      // > //
      const userRouter = require('./routes/User');
      app.use('/api', userRouter)
      // Listen
      app.listen(3001, () => { console.log(`Running on port 3001`) })
      //*********** USER ROUTER **********/
      const express = require("express")
      const router = express.Router()
      // Database Connection
      const db = require("./../connection/conn")
      // Login Route
      router.post('/login', async (req, res) => {
      const username = req.body.username;
      const password = req.body.password;
      const fecthUsersQuery = "SELECT id, username, password FROM users";
      db.query(fecthUsersQuery, (err, results) => {

      if(err){
      return res.json({
      status: 'bad',
      message: "Something went wrong"
      });
      }
      for(let user of results){
      if(username === user.username && password === user.password){
      const accessToken = createTokens(user);
      res.cookie("access-token", accessToken, {
      maxAge: 60 * 60 * 24 * 30 * 1000
      })
      console.log(req.cookies["access-token"]);
      return res.json({
      status: 'good',
      message: "Test"
      })
      }
      else{
      return res.json({
      status: 'bad',
      message: "Username or password does not exist"
      });
      }
      }
      })
      })

  • @madhushreekunder7727
    @madhushreekunder7727 2 года назад

    Thanks A lot!!! Really good video!

  • @anoirtayeb8791
    @anoirtayeb8791 3 года назад

    Hi perdro,
    can you tell me please , after the authentication , how can i pass the username and id from login to profile .

  • @henriquekutner6724
    @henriquekutner6724 2 года назад +1

    This is gold

  • @vivekpaliwar7217
    @vivekpaliwar7217 3 года назад

    can i do this with react as frontend and use MySQL as database

  • @minegamer369
    @minegamer369 3 года назад

    What’s your vs code theme ?

  • @gustavocapistrano7376
    @gustavocapistrano7376 Год назад

    Amazing tutorial!!

  • @okaforjaachi9203
    @okaforjaachi9203 8 месяцев назад

    you didnt show how you setup your workbench

  • @Thami250
    @Thami250 9 месяцев назад

    Thank you man 👌👌

  • @002ashishkumar5
    @002ashishkumar5 3 года назад +1

    superb explaination thnx

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +1

      Thanks and welcome

    • @002ashishkumar5
      @002ashishkumar5 3 года назад +1

      @@PedroTechnologies can you please make a vidoe on how to automatically logout the first device when second device gets connected 😊😊

  • @louislecouturier
    @louislecouturier 3 года назад

    Hey Pedro ! How can you get httpOnly cookies with React ?

  • @ricardotech
    @ricardotech 3 года назад +1

    Brabo irmão!!

  • @bfrAliShettima
    @bfrAliShettima 6 месяцев назад

    The video is educative

  • @jiteshjoshisde3154
    @jiteshjoshisde3154 3 года назад

    Great pedro ❤️❤️🙌🏻🙌🏻

  • @manolisgkoulias8290
    @manolisgkoulias8290 3 года назад

    thanks a lot!

  • @PanlasangMotour
    @PanlasangMotour 3 года назад +2

    Noice go go go

  • @kishankumar2272
    @kishankumar2272 8 месяцев назад

    Thanks ❤

  • @brahimwebmaster
    @brahimwebmaster 3 года назад +1

    great Thanks :)

  • @leahisrael2956
    @leahisrael2956 3 года назад +1

    Amazing!!

  • @tejass817
    @tejass817 2 года назад

    great content

  • @yilmazahmet8767
    @yilmazahmet8767 2 года назад +1

    Teşekkürler.

  • @nithinprathapan5564
    @nithinprathapan5564 Год назад

    Thankyou

  • @rangabharath4253
    @rangabharath4253 3 года назад +1

    awesome

  • @f3-faithfitnessfinance
    @f3-faithfitnessfinance 3 года назад +1

    Do you have a job now, Pedro ?

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +3

      Yeah, after months of studying interview questions I got an internship at Twitch hahaha

    • @f3-faithfitnessfinance
      @f3-faithfitnessfinance 3 года назад +1

      @@PedroTechnologies That's so cool

    • @_chidiebere4763
      @_chidiebere4763 3 года назад +2

      @@PedroTechnologies so cool. I am haapy for you. Keep hacking!

    • @PedroTechnologies
      @PedroTechnologies  3 года назад

      Thank you! Really appreciate it!

    • @PedroTechnologies
      @PedroTechnologies  3 года назад +1

      Thank you so much! The support you guys give me is unimaginable!