React Persistent User Login Authentication with JWT Tokens

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

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

  • @DaveGrayTeachesCode
    @DaveGrayTeachesCode  2 года назад +28

    In this series of videos, we've been creating a full React registration and login authentication system. We've built registration and login forms, applied protected routes that respond to user roles, and implemented continuous JWT authentication. Now, we'll add login persistence to the app so a page refresh - or even navigating away and returning - will not logout an authenticated user who has a valid refresh token. This solution does not use localStorage or sessionStorage for JWT token storage. If you haven't, I recommend starting at the beginning of this auth series playlist: ruclips.net/p/PL0Zuz27SZ-6PRCpm9clX0WiBEMB70FWwd

    • @miguel5088
      @miguel5088 3 месяца назад

      Please I am stuck

  • @victoronwe906
    @victoronwe906 2 года назад +115

    This is simply a top notch premium content. Maintain this path and soon you will be the biggest react channel on RUclips. To be honest most paid courses on udemy do not give as much value as you have. Thanks for your great job Dave.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 года назад +9

      Wow, thank you so much for the kind words! 💯 I'll keep going! 🚀

    • @siddiqahmed3274
      @siddiqahmed3274 2 года назад +5

      yes it is truly top notch. nobody I have come across is making such high quality tutorials. God bless you SIR. And thanks a million ❤

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 года назад +5

      @@siddiqahmed3274 thank you!

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

      @@siddiqahmed3274 Exactly, and this is the channel advantage

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

      @@DaveGrayTeachesCode Excellent. Am really looking forward for you to build a project with production structure. Something with different layouts, loading state, state management, error handling etc. Any project that is well crafted for production will greatly be appreciated. Plus you can reach out to Traversy media and publish such project on his channel. I believe it will add atleast 10k subscribers to your channel.

  • @ebratz
    @ebratz 2 года назад +22

    This kind of intermediate/advanced tutorials are much appreciated. Keep the awesome job coming!

  • @Ulasp
    @Ulasp 5 месяцев назад +1

    Hey thank you a lot for these videos, they are really helpful!
    I've been following the series adapting it to a project im working on with typescript, so far everything was working until now trying to do the persistent login authentication, it seems after refreshing the page, the auth data is lost and sends undefined forcing me go back to login page, even with the PersistLogin component and that, I would appreciate some help im stuck

  • @mitpancholi8089
    @mitpancholi8089 2 года назад +9

    This tutorial has it all you need to create standard login flow, and I realized that this is how it should be done. In real situation security is often overlooked. Every bit of this video is precious with advanced material.
    Thanks for sharing 👍. I binge watched this series of tutorials 😂

  • @TanveerAhmed-b7s
    @TanveerAhmed-b7s 10 месяцев назад +2

    Hi Dave, great content. one question. In the previous tutorial you mentioned that we should store the access token in app state and refresh token in http only cookie. I cannot find where you have actually stored the refresh token on the frontend. all I get is that you call the /refresh endpoint without any token and you get back the new access token.

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

      The refreshToken was stored as an HTTP only secure cookie at the backend. In summary, the backend supplies it upon authentication(log in) but you can't see or access it in the frontend. You can check the source code of the node REST api used for this tut, it's right there.

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

    Dave Thanks for the tutorial. When Using UseEffect to get data using the useAxiosPrivate and the abort Controller, it fetches the data, but returns error. Why is it like this? and why should i use a abort controller

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

      I'm guessing you are using React 18 and this tutorial was made with React 17. The why and how to fix is discussed here: ruclips.net/video/81faZzp18NM/видео.html ..as for the AbortController, I discuss in a few videos (like this one when I update the useAxios hook for React 18: ruclips.net/video/N41B_SVdzwg/видео.html), but you can always reference MDN as their documentation is great: developer.mozilla.org/en-US/docs/Web/API/AbortController

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

    29:28 Suppose I don't want to include isLoading in PersistLogin Component. Then the condition will be
    {
    !persist
    ?
    :
    }
    If the persist is true then show the Outlet, if persist is false then also show the Outlet, then how do we differentiate whether we trust the device or not. My humble request to you sir, Please explain this once.

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

    This is so much fun! I have been rewriting this for Azure CosmosDB NoSQL API and Azure Table and removing axios in lieu of fetch to remove dependencies. Next is to use TypeScript. I wish I started this tutorial by making it typeScript, but after this auth series I'll have a couple foundations to work with! Thanks for the backend! I am learning a lot about Node.js and I love it!

  • @nurettinsen473
    @nurettinsen473 10 месяцев назад +1

    "Why do you think we should store access tokens in React context as memory instead of sessionStorage? Can you explain why not store them in sessionStorage?"

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

    Hi Dave, your tutorial help me a lot but i have an issue, if user logged in my app and they type "login" in the url, its still back login page, i want check if user is logged then they type login in url its redirect to dashboard page, can you give me some solution

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

      Move on to the next tutorial in this series to better understand routing.

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

    React 18 is mounting useEffect twice even with [], which is causing the axios calls to be canceled and called a second time.

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

      This only happens in development with strict mode. Discussion and fix here: ruclips.net/video/81faZzp18NM/видео.html

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

    Thanks for this, now I can build entire login and signup using React and JWT for production.

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

      Absolutely! I'll look forward to seeing what you create! 🚀🚀

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

    Thanks for you tutorials, I learnt a lot from you, I have one question and hope you would answer me:
    if someone logged in without toggling "trust this device", and let's say he closed the browser at any time or the tab, then if you visit the website and toggle the "trust this device" then hit reload, wouldn't that send the stored refresh token then re-auth the previous user?
    I'm using react with .NET as backend
    could you help me with recommendation for solving this problem? 😅
    thanks again

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

    sir how about if the route is containing only user info and that user info is coming from the "{ auth } = useAuth" then the refresh token has expired when we visit the route that containing only user info it will not trigger the "verifyRefreshToken" because the user info is only coming from the "state"? like profile page that needs only user information so we can get that from "{ auth }" state right? so example the refresh token has expired and we visit the "profile" page it will not trigger the "verifyRefreshToken" as long as we don't refresh the browser or visit the another page that will triggering the inceptors

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

    Hi Dave. Nice video, but two questions!:
    1) If the user doesn't toggle `persist` to `true` and logs in, they still receive a persistent refresh cookie. As such if they logout, then toggle `persist` to `true` and refresh the page, since the refresh cookie still exists in the browser, won't the the user get logged in again? If so, how can we prevent this?
    2) Since refresh tokens are being recorded in mongoDB, if an authenticated user hits the `/logout` endpoint (but their refresh cookie has expired and therefore wasn't sent along with the request), how can we remove this expired token from the database?
    Thanks in advance, and keep up the good work! :)

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

      Thanks Alex! 🙏
      1) It would be a good idea to send a logout request with the logout action that will ask the server to "clear" (aka delete) the cookie. You can see an example of this in my current MERN Stack Project series: ruclips.net/p/PL0Zuz27SZ-6P4dQUsoDatjEGpmBpcOW8V
      2) This is a good discussion and something I have discussed in the comments for my Node.js JWT Rotation and Re-use Detection video here: ruclips.net/video/s-4k5TcGKHg/видео.html ...it would also be a good idea to have a maintenance routine / function that eventually removed old tokens from the data. Often JWTs are used in a stateless manner - not stored in a db at all - but with re-use detection, you have to keep track of the old ones.

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

      @@DaveGrayTeachesCode ​ Hi Dave, thanks for answering! I will check out the re-use detection video :)
      With respect to point 1), while I understand the use of `res.clearCookie` on '/logout', I'm specifically talking about refreshing the page while logged in (with `persist` === `false`), getting kicked back out, then toggling to `true` and refreshing the page and getting automatically logged back in again.
      I think this is happening because the a page refresh does not clear the site cookies, namely the refresh JWT.
      This is what's happening for me haha! If this isn't what happens in your app, no worries, I'll rewatch again :) Thanks!

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

      did you found a solution for the first point? 😅

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

      @@alext8593 I was searching for this question! The user better hope they remember to log out in such a case! xD

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

      @@MeAsMeButMe have a little message in the navbar saying "don't forget to logout" lmao

  • @r1shabhnegi
    @r1shabhnegi 6 месяцев назад +1

    this was an amazing lecture, I learned a lot from you Dave.

  • @noone_and_nobody
    @noone_and_nobody Год назад +3

    Started the series sometime last evening and continuing this first thing early in the morning. Great work Dave! And thank you very much for this.

  • @varshithgowdav9892
    @varshithgowdav9892 Месяц назад

    Hi Dave,
    How does adding simple check prevent user to reverify
    the useEffect in persistLogin runs regard less of how we are loading a component and there will be http only cookie that will help in persisting user the user.

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

    Is there any way that I could workaround using localStorage?

  • @teemofan7056
    @teemofan7056 2 месяца назад

    so what if i first login with persistent unchecked, then i refresh (should see the login page) and only check the persistent box. next I simply refresh, will this automatically log me in?

  • @shivaakrish
    @shivaakrish 2 месяца назад

    @30:00 How is it skipping the verifyRefreshToken call when we add the !persist check ?

  • @danyeun01
    @danyeun01 Месяц назад

    if anyone else if having issues because of react 18 strictmode, you can use a useRef to ensure the useEffect in PersistLogin only runs once. otherwise, im not sure what other solution would be viable.

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

    Hi Dave I noticed that when refresh the page with trust this device set to false our session cookie is still in the browser (even if we are redirected to the login page) and if we set persist to true manually via chrome dev tools we can still continue our session isn't this a big security concern?

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

      You can create a logout route that will delete the cookie. Otherwise, it will expire at the given time. Other measures can be taken - maybe try to clear browser history on logout or when a browser or tab is closed. There are lots of what-ifs here like what if a user walks away from the browser and doesn't log out? You are left with the expiration only. It is difficult to babysit every instance. If there is a huge security concern, my suggestion is to explain to the boss this feature can hurt the security of your app. Nothing in the frontend is 100% secure.

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

      I'm also concerned about this issue. If you have a refresh token that last a longer time and can be used in a public area, you can put manually to true and reuse. How about trying to logout if you are accessing to the app with persist = false and having a refresh token? It may add latency if persist is false and not having an access token but add better security maybe?

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

    Hi Dave. Thank you for the amazing tutorial. It has helped me learn a lot.
    I was wondering if the same concept can be implemented when a user has multiple devices. This is because each login will update the refreshToken in the database and render existing login in a another device invalid.

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

    Note for anyonne getting an error like : Unhandled Rejection (SyntaxError): Unexpected token u in JSON at position 0
    If you have this error you may not need to parse the JSON in the persist state of AuthProvider.
    So go from this..
    const [persist, setPersist] = useState(JSON.parse(localStorage.getItem("persist")) || false);
    .. to this..
    const [persist, setPersist] = useState(localStorage.getItem("persist") || false);

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

      this worked for two tries then it stopped, is it still working for you?

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

    Great job Dave! Question - does the refresh token / set-cookie header also persist on the front end on a page reload? If so, is that cookie then used to get the new access token? Since local storage is not used to store the user or access token and the app's memory is wiped, I'm unsure how the re-login works.

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

      Hi Ian - I think you've got the idea. The cookie is all that remains when a refresh/reload clears the auth state. Same for navigating away and returning. When you return, if you have chosen to persist your login, the cookie is sent to the refresh endpoint. If the refresh token has not expired, a new access token is issued which allows continued use. You can send the data you want - maybe a username or roles - inside the access token or outside. Later in this series, I recommend inside.

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

      Exactly mate, the httpOnly cookie persist on the browser until the client removes it from the browser or it expires (remember the backend defines a maxAge for the cookie)..

  • @ЮрийНосов-щ8ц
    @ЮрийНосов-щ8ц 11 месяцев назад +1

    Thank you for your tutorials

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

    great video, is cookie/session auth dead nowadays? can hardly find any quality videos explaining cookie/session. instead 99% are JWTs...

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

      I wouldn't say dead, but JWT is a popular choice - especially for use with REST APIs.

  • @HarmanSingh-tp7xs
    @HarmanSingh-tp7xs Год назад +2

    Great Content Sir ! Best Playlist to understand JWT handling on Frontend. Recently finished your Nodejs Course, loved it !😇

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

    hi Dave, how if we have 3 login method in our app, login with username and password, login with google, and login with facebook. Is the jwt access and refresh token still needed in the other 2 login method (google and facebook) ?

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

      You do want to stay consistent. If including social logins, look into a solution like this that supports social logins and JWTs: ruclips.net/video/pAzqscDx580/видео.html - this tutorial does not show the JWT implementation, but they do support it.

  • @ggsgetafaf1167
    @ggsgetafaf1167 4 месяца назад

    thank you very much for your video. I learn a lot from it. but I have one question:
    In Component PersistLogin:
    {!persist ?
    :
    isLoading ?
    Loading ... :
    }
    To be honest with you, I do not understand why *persist* is false --> go to login page?
    After debugging (ignore StrictMode), I see:
    - If persist is *true*, the component will render *2 time* (one for the initial and second after having new access_token).
    - If persist is *false*, the component only renders one time although useRefreshToken hook still is called and updates auth through setAuth

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

    I got a little confused about the logic used when we implemented the persist state in the PersistLogin component:
    !persist
    ?
    : isLoading
    ? Loading...
    :

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

      Same here

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

      I'm not getting how this is working, even if persist value true or false he is showing the
      The useEffect will still make the refresh() API call.

    • @danyeun01
      @danyeun01 Месяц назад

      @@coolme7437 late but also wondering the exact same thing. did you figure it out?

    • @coolme7437
      @coolme7437 Месяц назад

      @@danyeun01 ask GPT

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

    Unless I've done it wrong, the persist/isLoading chained ternary check still results in the verifyRefreshToken function being called whether persist is true or false - so even though access is not granted to protected routes, a token is returned from the server and stored in state - and in my case, so is some user info. A bad actor could see this data in the request response if they used the console. I fixed this by (in my case) checking for the persist state in the useEffect instead so that if persist isn't 'true', the verification function isn't called at all.

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

      I also got stuck at the same point. IDK how it worked in his system.
      I figured it out while watching the video.

  • @MP-ni2qf
    @MP-ni2qf 3 месяца назад

    Can you help me? When I setAuth(prev) is return nothing even though there is respone.data in it

  • @kirillzlobin7135
    @kirillzlobin7135 7 месяцев назад

    35:05 - Important error fix - Cannot Perform a React state update on an unmounted component

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

    Hi Dave, I love your videos. I have a problem, my useEffect is executed twice because of react's strict mode, so my fetch to update the token is executed twice simultaneously which causes the second call to try to delete the cookie that the first one already deleted and this ends up generating an error.

  • @dark-dew
    @dark-dew 2 года назад +1

    Hello, Dave. The tutorial is great. I have a question. While logging out, if user doesn't have internet connection or if the logout request to the server fails then the cookie won't be cleared but user will be taken to login page. Now, if user again goes to protected routes then he/she will get access even if he/she has logged out.
    Shouldn't we check if the logout request to the server was successful before redirecting the user to login page?

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

      That's a good idea! The temporary situation you describe will only be possible before the token within the cookie has expired, but it sounds like it is possible. 💯

  • @MinhLe-lc7tk
    @MinhLe-lc7tk 2 года назад +1

    Hi Dave, thanks for your great tutorial.
    Will there be also a tutorial for Persistent User Login Authentication with JWT Tokens but with Redux Tookit and RTK Query? It would be fun, i think.

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

    Great tutorial, followed it from beginning to end it was basically flawless! Learnt a lot and your teaching style is easy to follow and very consistent. Thanks a lot for this you earned a subscriber.
    PS. is it possible to know which vscode theme you were using in this video? thanks!

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

      I am currently using the Github theme for VS Code and I think I used it in this video, too.

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

    David, thank you for your great in depth tutorial. I sure could pick up a lot of things for my project so many kudos to you! I do have one question though and I really hope you can find the time to react (no pun intended, but haha!). When I refresh the page (the browser, like with the f5 key), the auth object (state) will become empty, and filled with roles and the token. In the useRefreshToken hook, you make use of ...prev in the return, but when I console.log prev, it's an empty object (after browser refresh), and therefore not restoring my set username. I can fix it by passing user in the refreshTokenController, but I really would like to make use of ...prev. Did I miss something (I do think I've looked everywhere) or can you (or any user in here!) help me out how to make it work without saving the state to local storage? Many thanks and keep up the great work! You mean a lot to us
    edit: eventually I want to only use ...prev and accessToken, as ...prev should already have the username and the roles in it and only overwrite the accessToken. I hope you understand what I'm after :-)

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

      Good questions! You will always lose app state when you refresh or when you navigate away from the app and return. Anything you want to persist needs to come from the server. You can send it all inside the access token and decode the token when you receive it. Keep going to the "best practices" tutorial in this series for recommendations on that.

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

    Best Series out there! Thank you Dave. Loving your content

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

    Excellent work Dave.
    But I have a question in mind. Suppose, someone doesn't "check trust this device" and left the computer and still access token is not expire.
    In this senario, if someone else change the localStorage value to TRUE via application tab. Now the person will have the access and will remain loge in.
    Please, do correct me if I'm wrong.

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

      Ideally, your user signs out or closes their browser in a public setting. Of course, you cannot guard against everything a user may do. At your suggestion if the user did not log out or close their browser, a hacker would need to know to go to the local storage setting, change a specific setting, and if successful, they may gain access for the short time before the access token expires which I recommend giving a span of no more than 15 minutes. Consider a banking website as a real world example, if I don't log out or close my browser when I leave the computer, access remains for a limited amount of time.

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

      @@DaveGrayTeachesCode Thank you for the explanation. 🙂

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

    Bro you're the best
    Greets from indonesia

  • @mikebarbre6523
    @mikebarbre6523 11 месяцев назад

    Great tutorials. I'm still trying to decide if REACT is worth the headaches. For example, with this lesson, I keep getting an invalid hook error at Object.throwInvalidHookError (react-dom.development.js:16227:1)
    at useContext (react.development.js:1618:1)
    at useAuth (useAuth.js:5:1)
    Not asking for a solution, but just trying to decode what the error is saying and how to find the issue is taking a lot of time.

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

    Thanks Dave, your videos are great! You're really the only one out there who addresses security to this level while going through tutorials.

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

    I would recommend this playlist it's so informative. Well explained and the example code is clean.

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

    Dave, please, please, please. I need help...
    For example, when we reloaded the page - we lost all data. The only thing we have - is just a refresh token. So, we will use this refresh token to get a new access token from /refresh endpoint.
    But how do we get the information about the user? Now we have only token. But if we want to show some user info? Like email and profile photo. Isn't this information is also sent when we log in and kept in memory?
    So our refresh endpoint should also send this, correct?
    Otherwise we should keep user's info in a localstorage

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  6 месяцев назад +1

      The new access token lets you access the other information you need. Do not store any sensitive user data in localStorage. It is not secure.

  • @soy-luisarrieta
    @soy-luisarrieta Год назад

    Dave, my persistent user login is not working because my refresh token API requires a token to identify the user. PDD: Thank you so much for this playlist, it's amazing!!

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

    I'm not getting how persist is working?
    Why !persist was not applied in the useeffect before checking !auth ?

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

    When I refresh the page twice, i get logged out. If I refresh only once, I do not get logged out.
    This is the code for the Persistent Login
    import { Outlet } from 'react-router-dom'
    import { useState, useEffect } from 'react'
    import useRefreshToken from '../hooks/useRefreshToken'
    import useAuth from '../hooks/useAuth'
    const PersistLogin = () => {
    const [ isLoading, setIsLoading ] = useState(true)
    const refresh = useRefreshToken()
    const { auth } = useAuth()
    useEffect(() => {
    let isMounted = true
    const verifyRefreshToken = async () => {
    try{
    await refresh()
    }catch (err){
    console.log(err)
    }
    finally{
    // Avoids unwanted call to verifyRefreshToken
    isMounted && setIsLoading(false)
    }
    }
    !auth?.accessToken ? verifyRefreshToken() : setIsLoading(false);
    return () => isMounted = false
    },[])
    useEffect(() => {
    console.log(`isLoading : ${isLoading}`)
    console.log(`authToken : ${JSON.stringify(auth?.accessToken)}`)
    },[isLoading])
    return (
    {isLoading
    ?
    ...Loading
    :
    }
    )
    }
    export default PersistLogin

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

    Can you help me sir, when i add another route in front-end to display users in another page, it returns 401 in backend, I can't receive access token in auth header in verifyJWT, only the homepage can fetch the data and working, thanks in advance 🙏

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

    Hey dave, Its working perfectly with the localhost backend endpoint, but the cookies somehow doesnt work with a EC2 hosted backend endpoint.

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

      Possibly http on localhost vs https when deployed. secure: true in the cookie for https.

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

    You are very clear and thorough in your explanations. Very much appreciate your content!

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

    Hi would appreciate if you can Add typescript to your react project,bcz typescript mern stack advanced project are very rear ,please consider this for future projects,

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

    If You check to not trust the device, log in, then refresh page, then type manualy secured route that was viable for just logged out user, this will authorize him and grant new token, thus logging him in anyway

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

    Great lecture as always! I have always benefitted from them.
    I was just thinking it might be possible to store both access and refresh token in the cookies rather than sending the access token as request. I ask this because I come from the redux toolkit auth tutorial and there if I use redux persist I would have use local storage or so. I really dont want to store anything on the local storage as I feel it is not so safe? Whats your take?

  • @ChandujobsApplications
    @ChandujobsApplications 7 месяцев назад

    No udemy could teach this much high level content....... even stephen grider also could not give this much high level content...... thank you sir!

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

    Hey Dave! Thanks for doing this intermediate react tutorials, they are so valuable! I have a question, on the Login component, on line 45, we set the Auth using setAuth and we store whats coming from the backend, the roles and the accessToken, but we also store the user and the password on the state of the app. This is not neccesary, right? since we are checking if there is an accessToken inside the auth.accessToken state, user is no longer needed, and the password either, correct? this was just for console logging purposes?

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

      As far as I remember, you are correct. There is no harm in storing a username in app state if you want, but I don't suggest that for a password. There are a few more videos in this series and one is where I suggest some best practices which addresses this in more detail.

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

    Thanks for your sharing a nice video , if we use Spring Boot API what should we do ? if i can use this please tall me ?

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

    Why I refresh the page, my backend server receive an empty token? Any help will really appreciate !!!!

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

      I can only guess about your code from here. Compare your code to the source code available for the video at the link in the description. If you don't see a difference, use a tool like diffchecker.com

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

    you explain very nice.

  • @sundayucheawaji6206
    @sundayucheawaji6206 4 месяца назад

    Thank God I came across this channel. I really learnt a lot. Thank you very much, Dave. You are truly an inspiration to many.

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

    Hi Dave my RequireiAuth is not waiting for the Persistent login to complete is component is redirected to login while auth is still stil waiting for data

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

      You might compare your code to my source code linked to in the description. Another consideration is React 18 strict mode which will mount and unmount each component before remounting. Remove it from your index.js for a quick fix. For a better fix, I have this video: ruclips.net/video/81faZzp18NM/видео.html

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

    I still dont understand how the persist works ... where does it get the accessToken information when the page is refreshed ????

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

      I think you would understand better by understanding how the backend REST API works. You can learn how to build it here: ruclips.net/video/f2EqECiTBL8/видео.html

  • @AhmedRaza-ll5yv
    @AhmedRaza-ll5yv 7 месяцев назад

    In my case, its sending refresh token request everytime I refresh the page. Is that normal?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  7 месяцев назад

      Yes, that is intentional. When you refresh the page, you lose all client-side state. It's like rebooting an app. You must send the refresh token upon refresh to remain logged in.

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

    hi thank you for time and teaching. Do you have github for downloading the code ?

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

    How when the access token is expired then without reloading it’s logged out??

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

      If I understand correctly, you want to log out a user automatically when the access token is expired? You can do that by using a library like jwt-decode in the client, but usually, you just wait until another request is sent to the server and log the user out when the tokens fail. This allows a check of both the access and refresh tokens.

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

    hello, im newbie and have a question, is this works if backend and frontend at different server ?

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

    hello dev, is accesstoken stored in memory, if so is it secure to xss attacks! please reply😅

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

    When I refresh twice, It logs out again? Any tips?

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

      Check how long your refresh token expiry is set? It shouldn't matter how many times you refresh if your refresh token is not expired. Also, you could have a React 18 strict mode double mount issue. This tutorial was made with React 17. I cover that here: ruclips.net/video/81faZzp18NM/видео.html

  • @wasitjamal7392
    @wasitjamal7392 7 месяцев назад

    I have a question. At 14:34, when testing you press refresh but how does it send a refresh token in request if the auth state is lost in refresh?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  7 месяцев назад

      The refresh token is stored in an httpOnly secure cookie - not in state.

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

    I feel like you are the only youtuber who post what I'm looking for my projects. Great Job👍👍👍!

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

    This video is not playing. Anyother way I can access it?

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

    This being your last edition to React Login Authentication Series, I have to put my comment here. I have used all of your 5 series to develop a full working React JS Admin Web application (deployed on Digital Ocean) with little-to-zero background in React JS. Since I used Spring Boot as the backend, access token refresh withCredentials=true (cookies) didn't work for me (as I have other custom headers, and an Android app consuming the same APIs) and therefore opted to go with storing the refresh token in the local storage. I know this is a huge security flaw by design but as of now it is working fine for me and I'm okay with it (as I explore a more secure way to do it).
    I must admit that your tutorials are so straightforward, simple to follow, relevant and so resourceful (to an extend that I have added them all to my playlist). All my credit therefore comes back to you, in retribution, for the wonderful work (I wish I could buy you coffee 😊) and will continue watching more of your videos, Sir !

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

    Very helpful! Just wanna ask though, how would we prevent an authenticated user from accessing some of the public routes like login page or sign up page when manually typing in the URL or using the browser's navigation for those routes? Thanks!

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

    Awesome series of tutorials. Can you implement logging in multiple devices.

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

      That's a good request! It would require more changes to the backend node.js code to put in place.

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

      @@DaveGrayTeachesCode Thanks for considering the request. It will be good tut for extending the feature.

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

    Hi, i have a problem. My useEffect isMounted 2 times so axios send 2 requests for /refresh but we have a res.clearCookie at the top of /refresh function. I have error: useEffect with axios make 2 requests but the second requests dont have cookie so /refresh return 401. U know how a can fix this. On internet i see i need to remove React.StrictMode and its working but its nots recommended right ?

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

      Search my channel and you shall find 😀: ruclips.net/video/81faZzp18NM/видео.html

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

      @@DaveGrayTeachesCode OMG thank you very much, i'm self-haught, sometime it hasn't been simple and still learning english ahah. You are the best Teacher on internet, thank you a lot for this premium content!!

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

    How i can retrieve the user username to show it in other places of the app?

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

      I assume you mean after you refresh the app and then use the login persistence by sending the refresh token... If so, your backend can send the username back inside the access token to decode - or outside of the token if you wish.

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

    what happens when the user goes to login page when he is already logged in?

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

      Did you try it? If I remember correctly, I left it alone. You could check for a login and redirect accordingly OR you could assume the user wanted to go to the login page and let them go.

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

    THANK GOD YOU EXIST

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

    Hi Dave, thank you so much for all your classes. It is really the best classes I found online. I followed your training on Persistent User Login Authentication. I'm using React 18 and I find out that if I'm replacing ReactDOM.render with root.render (as suggested in version 18) it is not working. I'm getting "Canceled Error" from the backend and getting back to the login. Will appreciate if you have any suggestion. Thanks in advance

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

      You must be using StrictMode. In React 18, strict mode renders twice. That means the component unmounts once and calls the useEffect clean up function which calls the abort controller to cancel a request.

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

      @@DaveGrayTeachesCode Thank you so much, this was the issue.

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

    Please add the link to backend repo in the description

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  10 месяцев назад +1

      It's in the description. The node.js course builds it.

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

    If the persist is false then move to outlet and if persist is false and isLoading is true then show the or else again move to outlet. So my question is when the verifyRefreshToken () will execute?
    If verifyRefreshToken () execute while we use PersistLogin component, as the dependency is [], and if persist is false then verifyRefreshToken() will work or not?

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

      It has been awhile since I made this, but in general, verifyRefreshToken is called when axios intercepts a request where the auth token is denied.

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

    I have a BIG problem 😨😨😨JWT Cookie is setted in Postman but NOT in browser ?? what could be wrong ???? (i have withCredentials: true)

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

      In the Node JS repository, the secure option on the cookie is not set. As noted in the Node JS course, the secure option was //commented for testing with ThunderClient. I'm just guessing, but if you downloaded the code and did not change this in the authController, it is the likely cause.

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

    excellent thank you !

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

    I don't know if anyone else mentioned it but when you logged in persistent , you encounter a problem in logout implementation. Firstly you logged out but after refresh the app return the user in some way i dont understand. After an hour looking for the problem and solution of it in server and client , the solution i found is add "localstorage.setItem("persist",true)" in the logout hook after the setAuth line. If anyone knows the reason behind this problem , i would appreciate to hear it.Good days.

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

      Insure your Node.js code deletes the cookie in the browser when you send the logout request. This will insure the user is not logged back in even if persist true is set. This is especially important on shared computers.

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

      @@DaveGrayTeachesCode thanks for your answer , you are great human.firstly , I use spring and i do clean the cookie in the server when logout but it didnt work as expected , i think problem could be on routes(react-rd) but i dont know. For now , it works and im happy 😀 when smthng go wrong i let u know.

  • @mikutaa
    @mikutaa 7 месяцев назад

    This is the best explanation of the authentication mechanism I've ever seen. Thanks!🙏

  • @miguel5088
    @miguel5088 3 месяца назад

    Please can anyone help me

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

    What if we are visiting our app next day and refresh route also returns 401. So the time during which we could refresh has finished (or our refresh token is also dead). We would need our application logout automatically then redirect and show only Login Page. Do you have that behaviour in this course?
    Also will this app work if my backedn expects Bearer token?

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

      Bearer token is the access token. Not sure what other videos in this series you have watched, but links to all in the description, and I show how the access token is sent as the Bearer. These videos are for understanding the concepts, but you can configure in different ways. When your tokens are expired, you will be redirected to the login.

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

    Hi dave great tutorial. At 2:44 i notice in the console that it displays xr.js and the local host stuff. But in my app it shows the actual code of the React client app which is obviously not good for security. How do you get it to display just the request rejection and not the react code? Ideally I dont want the client to see that there was an error in User.js or whatever as they can click on the error and see my react code. Thanks

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

    A tip from me : if you are using react 18 version then it wont work because cookie disappear after refreshing the page ,and we go in the !foundUser loop in refreshtoken controller ...so to avoid this thing ,you should remove strict behaviour of react from index js file and then it will work fine ❤️❤️ i have solved it by doing that 😊😊

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

      I ran into the exact same issue, using version 18.2, it works on local but failed production. Glad to see your comment! Any side effect if removed strict mode?

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

      Actually, removing strict mode does not persist my cookies. It works on local but not on server. Any hints?

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

      @@yw3546 maybe you are doing something wrong with your code ,😊

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

      @@yw3546 its my first time to use this react version ,so i am still searching about that 😊 if you have found something about that then share it with me 😊❤️

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

      @@usmanshahid8529 Actually I found the root cause. To use SameSite=none you have to set Secure to true. And to use Secure=true you have to send through https or localhost. My project so far is still using http, so it works locally but not on production. It is a very interesting finding. I posted it to a separate comment as well.

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

    Hi dave . i using garbage php freamwork (laravel). this method u using for persistent User Login it is kind of ddos attack to poor mysql . is very good for nodejs and mongoDb developers. I wish you would say the localstorge method .tnx

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

      Some devs really like Laravel. PHP and JavaScript have many differences though. Specifically, PHP does not run client-side in the browser, so the approach to a login would be very different from what we have here.

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

    Your content & explanation is very good but I really don't like the idea of making our REST API stateful by storing jwt token in http cookie. Storing jwt token in http cookie does not help either when we got attacked by XSS. Because attacker can still make malicious ajax requests (with credentials:true) from XSS injected javascript codes. My honest question is... do you really store jwt token in http only cookies in your realworld production reactjs apps ? Thanks again for your great tutorials!

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

      You can do either depending on your strategy. Nothing in the frontend is 100% secure. I think you are at less risk of XSS by using the secure cookie strategy than you are from storing tokens in localStorage. JWT is often used in a stateless way without storing a reference to previous refresh tokens. However, if you want to use refresh token re-use detection, you need a reference store of previous refresh tokens. The backend used here does that ( ruclips.net/video/s-4k5TcGKHg/видео.html ) ...so again it all depends on strategy. There is no one specific correct way. More on JWT rotation and re-use detection here: auth0.com/docs/secure/tokens/refresh-tokens/refresh-token-rotation

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

    What exactly does the auth and setAuth state do in the AuthContext? I am trying to do this in typescript but the compiler keeps yelling at me saying the setAuth does not exist in the refreshToken hook. ):

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

      If I remember correctly, there is a custom useAuth hook that has the auth state. That is what auth and setAuth represent.

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

      @@DaveGrayTeachesCode so it just keeps track if the currently logged in user is authenticated? Like a true or false?

  • @Lykkos29
    @Lykkos29 7 месяцев назад

    amazing tutorial sir, so well explained that even the backend logic in some sections of this video that you're explaining is very clear that I'm applying to Spring Boot to make a logout and login functionality without the necessity of watching external tutorials for it! 10/10!!

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

    Great video series. But one question... when React, running in strict mode in dev, mounts and then immediately unmounts the Users component - that cancels the axios request. Doesn't that cause the catch block to run, which navigates the user to the login screen (line 24)? At least that's what's happening for me when I try this. Isn't that a bug?

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

      This tutorial was made with React 17 (check my package.json in the source code) before React 18 introduced the double mount in StrictMode. Nevertheless, it is not a bug. StrictMode only applies to dev mode. In addition, I provide a workaround here: ruclips.net/video/81faZzp18NM/видео.html

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

      @@DaveGrayTeachesCode Dave - thank you for responding so quickly, and with an exact, clear solution! (More importantly - *thank you* for all of these incredible videos. They are all phenomenally helpful, clear, easy to follow, and useful. I'm really grateful.)

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

      Hey I'm getting the same issues but i can't seem to find a solution. Did you happen to find one?

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

    we can also use redux with redux-persist? won't it make it much easier?

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

      Redux-persist uses localStorage. I don't recommend that for auth data.

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

      @@DaveGrayTeachesCode Thankyou so much.. this series is amazing

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

    Dave, i don't undestand how you persist jwt token in state after a refresh page. Do I really need a refresh token endpoint in my API to make this happen?

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

      You don't persist anything in state upon a refresh / reload. That resets the state. However, you should have a refresh token stored in a cookie - that's not state. It can be sent to the server on reload to once again get your auth data if the token is not expired.

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

    Hi Dave, thank you for the tutorials, I've gone through both the NodeJS and and React authentication series, and I've learned alot!
    Was just wondering if you've also noticed the "flicker" that happens once you click the sign out button on the home page? You can see it @21:38 in the video, the route is set to /login and then it navigates to /linkpage, as it awaits the logout and then navigates. Would you be able to explain why we chose await logout()?
    Thanks again!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 года назад +5

      Great question. When we logout, the RequireAuth component wants to send us to the login screen immediately. However, we also have React Router navigate us to the homescreen in this example. I'm sure this could be adjusted for a smoother experience. Maybe set a state value that RequireAuth references instead of always defaulting to the login page. Just one idea.

    • @Mohammedkhaled-zf1wr
      @Mohammedkhaled-zf1wr Год назад

      @@DaveGrayTeachesCode but here dave, requireAuth component shouldn't have been rendered beacaue we are heading to public route (linkpage) not private route? am I missing something???