Role-Based Authentication in React (Complete Tutorial)

แชร์
ฝัง
  • เผยแพร่เมื่อ 21 พ.ย. 2024
  • 🚀 Project React → cosden.solutio...
    📥 Import React (Newsletter) → cosden.solutio...
    Source Code → github.com/cos...
    Join The Discord! → discord.cosden...
    VSCode Theme | Font → Material Theme Darker | Menlo, Monaco "monospace"
    In this video we will learn how to handle role-based authentication in React. We will implement a custom AuthProvider component to handle authentication, and then a custom protected route component to handle user roles. Only if a user is signed in and with the correct roles, will they be able to view the content on the app!

ความคิดเห็น •

  • @Lykkos-321
    @Lykkos-321 2 หลายเดือนก่อน +11

    most cleanest react channel!! I needed this!!

  • @bestformspielt
    @bestformspielt 2 หลายเดือนก่อน +3

    I really love your channel and your very clean and simple way of writing code. This is the first time you took a slightly bad shortcut by using sentinel values for your context. Saying that "undefined" means one thing and "null" means another makes the code hard to read and reason about. A better way in my opinion would be an additional attribute in your context called "authState" which is an enum containing "pending", "authenticated" etc. This would make it way more obvious and intuitive.
    This is of course nit-picking. I still think your videos are the best react content there is. Thanks for making them. :)

  • @tomasburian6550
    @tomasburian6550 2 หลายเดือนก่อน

    Thanks for this. Auth has been my biggest weakness for the longest time.

  • @TannerBarcelos
    @TannerBarcelos 2 หลายเดือนก่อน +2

    Great implementation. I was talking to Claude about this recently and I came to a HOC solution which worked well, but this is simpler. Going to use this as a reference for a prod task at work 👀🍻

  • @Thomas-zr9uw
    @Thomas-zr9uw 2 หลายเดือนก่อน

    You really create the best content, real scenario's with best practices. Good reason for your channel to grow so well.

  • @pedrosilva2313
    @pedrosilva2313 2 หลายเดือนก่อน +1

    I'd recommend you to use the component from react-router-dom since we can add multiple routes to the same ProtectedRoute instead of adding multiple ProtectedRoute for each different route.

  • @jofay91
    @jofay91 2 หลายเดือนก่อน

    so happy i found your channel! great content as always!

  • @kevinchen9799
    @kevinchen9799 2 หลายเดือนก่อน +1

    Good video. But the title is wrong. It should be Authentication and Role based Authorization. Authentication is verifying if you are a valid user or not. Then comes Authorization. That is how they are defined in Computer Science

  • @gauravbawa5609
    @gauravbawa5609 2 หลายเดือนก่อน

    once again a great content and a very informative video, thank you so much

  • @grugbrain
    @grugbrain 2 หลายเดือนก่อน +1

    Very clear implementation. 🥰

  • @roman9266
    @roman9266 2 หลายเดือนก่อน +1

    exactly what I needed. Thank you!🤩

  • @Solo_playz
    @Solo_playz 2 หลายเดือนก่อน

    Way to 100k Lets goo you deserve more brother .... 🫡

  • @lil_nach
    @lil_nach 2 หลายเดือนก่อน +4

    I think you mean role based authorization right? The distinction between authentication and authorization is important

    • @cosdensolutions
      @cosdensolutions  2 หลายเดือนก่อน +1

      well the first half of the vid is all about authentication so I think the title is fine

  • @kermit4877
    @kermit4877 2 หลายเดือนก่อน +2

    Cleanest tutorial, greeting from Indonesia!

  • @muhammedsahad1612
    @muhammedsahad1612 2 หลายเดือนก่อน

    Best Channel for React

  • @ritankarbhattacharjee7661
    @ritankarbhattacharjee7661 2 หลายเดือนก่อน

    The video was awesome 👍. This is a per component based application right, I wanted to know that if we wanted to protect a complete route like /staff and its children /staff/profile, /staff/edit-profiles etc at once, then how will we do it? For projects where there might be many components that might need protection adding ProtectedRouteComponent like this may become a laborious task.

    • @cosdensolutions
      @cosdensolutions  2 หลายเดือนก่อน +2

      I would actually create one Route component and wrap all routes with it, and then have the logic there for any route. This is useful if you need to do other things to routes like set page title or analytics, it makes sense to have one component to do it! It's not laborious if every component needs it!

    • @ritankarbhattacharjee7661
      @ritankarbhattacharjee7661 2 หลายเดือนก่อน

      @@cosdensolutions got it thanks

  • @CLeovison
    @CLeovison 2 หลายเดือนก่อน

    Hi kosden, will it be possible in the future that you will make a video about implementing seo in react? Because that will be a really great great help, thank you so much

  • @codewithsanjay
    @codewithsanjay 2 หลายเดือนก่อน

    Great video, could you please teach us RBAC in next.js

  • @okadz7037
    @okadz7037 2 หลายเดือนก่อน +2

    Ty great tutorial 👑, i have a question, is the backend check role safer then this client side check, for example: in nextjs i check in the middleware or in the rsc pages, and redirect from there

    • @lil_nach
      @lil_nach 2 หลายเดือนก่อน

      Backend check is a must, he’s only included front end for brevity. If auth only lived on the front end, anyone could hit the backend using a script and do things they’re not supposed to

    • @cosdensolutions
      @cosdensolutions  2 หลายเดือนก่อน

      if you're using nextjs with rsc, yes you need to do that there as well. But if you're only on client components, for this specfiic use case it's just the frontend. But when logging the user in, you have to check their credentials and all other checks

  • @esmilcasado5923
    @esmilcasado5923 2 หลายเดือนก่อน

    I love your videos!

  • @challengerScat
    @challengerScat 8 วันที่ผ่านมา

    nice tut but this is insufficient cuz when handling multiple routes the currentUser goes back to null therefore you lose the ability to check for roles however you can use localStorage as an alternative to store the desired roles and then retrieve it when needed

  • @elabinnovations
    @elabinnovations หลายเดือนก่อน

    Thanks, but I'm stuck with GraphQL JWT auth. I'm using codegen and hooks for mutations and queries.

  • @pavlevelickovic2995
    @pavlevelickovic2995 28 วันที่ผ่านมา +1

    I love this implementations but i have one BIG question. The way you wrote this all login logic is in AuthProvider(including fetch itself) and although this look clean i run into a problem when i tried to make Login page. In order to show potential errors or loading state when user tries to log in i needed login fetch logic in my Login page component however you put that logic inside AuthProvider. I though of moving login fetch from AuthProvider to Login component and leaving just setCurrentUser and setAuthToken to AuthProvider. This way i will be able to monitor fetch state (show errors and loading state to user). Is this valid solution and if not please give me some advise.

  • @DShpak27
    @DShpak27 17 วันที่ผ่านมา

    Thanks for You work! But there is an error with statuses, in particular undefined in user. The author automatically fetches data through the use effect, in fact you receive authorization data only after sending the authorization form. It's bad that he did not simulate this in the example. It would have been a different matter, and so many will still have the task of really correctly processing authorization statuses in a protected route.

  • @pelumini
    @pelumini 2 หลายเดือนก่อน

    Great content, thanks

  • @mohamedsalimbensalem6118
    @mohamedsalimbensalem6118 2 หลายเดือนก่อน +1

    Can you make a video about casel

  • @dariorey8092
    @dariorey8092 2 หลายเดือนก่อน +1

    justo lo que estoy necesitando!!

  • @dhruvverma1001
    @dhruvverma1001 2 หลายเดือนก่อน

    Need "Project Next"

  • @wassimabdennadher2715
    @wassimabdennadher2715 2 หลายเดือนก่อน

    Great Job ! Can you please manage roles and authentication with redux

  • @mohamedyamani8502
    @mohamedyamani8502 2 หลายเดือนก่อน

    nice video!
    I implemented this once, but arrived at a situation I didn't like. In order to send the JWT with each request, I'd use interceptors for example, and since the accessToken is passed through context, the fetcher instance must also be a hook in order to access the token. This snowballs to each request you try to make, which must end up a hook.
    how do you deal with this?

    • @cosdensolutions
      @cosdensolutions  2 หลายเดือนก่อน +1

      I just created interceptors in useEffects in the AuthProvider directly that injected the authToken in every request and updated the interceptor everytime it changes. Then, the rest of your app just fetches as normally and the authToken will always be sent along!

    • @mohamedyamani8502
      @mohamedyamani8502 2 หลายเดือนก่อน

      @@cosdensolutions but the axios instances would need to be provided via a hook then, which in turn would require requests to be fired from within hooks/components, no?

  • @zlatkoiliev8927
    @zlatkoiliev8927 2 หลายเดือนก่อน

    10:58 why not directly call handleLogout() in the catch block in handleLogin. Seems like the logic is completely the same!

    • @cosdensolutions
      @cosdensolutions  2 หลายเดือนก่อน +2

      better separation of concerns. You don't log out the user when login fails. You log out the user when they are logged in and need to log out. It just happened that the logic is the same here but they are different use cases!

  • @BuddyTech-w2h
    @BuddyTech-w2h 2 หลายเดือนก่อน

    use context api with authentication with cookies, with axios only authentication user access dashboard with protected routes waiting for your response

  • @AbdulMajeed-lj3zi
    @AbdulMajeed-lj3zi 2 หลายเดือนก่อน

    Pleae make one video about Casal (Role Base Authentication) library

  • @randhir2588
    @randhir2588 2 หลายเดือนก่อน +3

    source code missing

  • @sunny7268
    @sunny7268 2 หลายเดือนก่อน

    can you cover jotai lib, it is great and to bad many do not know it is even exist.

  • @kalideb-y3y
    @kalideb-y3y 2 หลายเดือนก่อน

    isn't it bad when creating variable name same exactly as type name like the const AuthContext and type AuthContext? I am thinking to just lowercase the const like authContext, cause I am kinda confused when I see them

    • @cosdensolutions
      @cosdensolutions  2 หลายเดือนก่อน

      if you want them different, I'd rename the type instead!

  • @rohansachdeva627
    @rohansachdeva627 2 หลายเดือนก่อน

    How to handle situation where i need to show a different component on a page depending on the role type? Do you have a clean solution for that

    • @raves_r3177
      @raves_r3177 2 หลายเดือนก่อน +2

      after logging in, check user role, and redirect user to whatever route that role belongs (/admin if role is admin, /staff if role is staff). easy peasy

    • @rohansachdeva627
      @rohansachdeva627 2 หลายเดือนก่อน

      @@raves_r3177 no thats fine. But let say you have page wherein there are few components visible to both viewer and admin. And for admin role, there exist a special component, only visible to admin. How do you handle that in a clean way

    • @kalideb-y3y
      @kalideb-y3y 2 หลายเดือนก่อน

      role.admin ? : it's that easy?

    • @GenZ-Coder
      @GenZ-Coder 2 หลายเดือนก่อน

      Create a Condition render component something called like
      {chilren}
      Then render the children based on the given props of the component and you have higly generic customisable component wrapper that will only render a component based on a condition being true or any role matches the allowed roles in the props.

    • @rohansachdeva627
      @rohansachdeva627 2 หลายเดือนก่อน

      @@GenZ-Coder interesting 🧐

  • @MrGonzalezGerman
    @MrGonzalezGerman หลายเดือนก่อน

    great

  • @kalideb-y3y
    @kalideb-y3y 2 หลายเดือนก่อน

    can't this client codes be edited and then have access the protected route?

    • @cosdensolutions
      @cosdensolutions  2 หลายเดือนก่อน +1

      You would also protect your endpoints so even if they go to any route, they get errors from the api

  • @Rohan-hx7ry
    @Rohan-hx7ry 2 หลายเดือนก่อน

    How do i preview react website on phone when it's under development... Plz reply

    • @jerrykodes
      @jerrykodes 2 หลายเดือนก่อน

      In vite it comes out of the box by adding -host tag, not sure for nextjs but I believe you can search for port forwarding

    • @Rohan-hx7ry
      @Rohan-hx7ry 2 หลายเดือนก่อน

      @@jerrykodes thanks

  • @Shelton_fr
    @Shelton_fr 2 หลายเดือนก่อน

    The best

  • @pinoyolea
    @pinoyolea 2 หลายเดือนก่อน

    You mean Role based Authorization?

  • @himanshuchavda9887
    @himanshuchavda9887 2 หลายเดือนก่อน

    Next authentication in next.js

  • @kevinngugi6120
    @kevinngugi6120 2 หลายเดือนก่อน

    when my lead engineer sees me try to authenticate users on the client🤣🤣🤣 i might as well fire myself

  • @jacquelynecarmen
    @jacquelynecarmen 2 หลายเดือนก่อน

    ❤❤

  • @TrilochanSatapathy
    @TrilochanSatapathy 2 หลายเดือนก่อน

    Repo ???

  • @buddytech7775
    @buddytech7775 2 หลายเดือนก่อน

    Next video on context api with authentication with cookies, cookies store token user details with axios only authentication user access dashboard with protected routes waiting for your response (⁠◔⁠‿⁠◔⁠)

  • @MrJettann
    @MrJettann 2 หลายเดือนก่อน +4

    This is bad implementation of authentication, there are no cookies, access or refresh tokens, so it simply makes requests on every page refresh

    • @reskort4089
      @reskort4089 2 หลายเดือนก่อน

      Would you mind to tell me the resource about how to do it properly? This FE and BE things still kinda new for me. I really appreciate it sir. Thank you in advance.

    • @MrJettann
      @MrJettann 2 หลายเดือนก่อน

      @@reskort4089 to be honest I can't find any valuable information about it. Most of posts or videos about "how to eat make auth with Google or GitHub provider" and no one use credentials with tokens, only one thing I can suggest to you is try to search for axios interceptors with refresh and access tokens, it will be at least near to real world. It's not perfect, but working, especially in react

    • @cosdensolutions
      @cosdensolutions  2 หลายเดือนก่อน +7

      This video is about role-based, not pure auth. If you want interceptors and tokens, check out my main auth video

    • @reskort4089
      @reskort4089 2 หลายเดือนก่อน

      @@cosdensolutions i see, thanks for your respond, author.

    • @MrJettann
      @MrJettann 2 หลายเดือนก่อน

      @@cosdensolutions alright, but it still strange implementation of that :)