Role-based Authentication in NextJs 13 using NextAuth

Поділитися
Вставка
  • Опубліковано 22 жов 2024

КОМЕНТАРІ •

  • @usmansoomro4668
    @usmansoomro4668 Рік тому +9

    Sir you are very talented teacher. you followed the different path of teaching web developement.

  • @amankch
    @amankch Рік тому +4

    We can check if user is sign-in, returning Boolean from authorized Callback, and user's role and rewrite the URL with "/denied" page inside middleware function. So if user's role is "user" and is signed-in, he/she try to visit some protected route, we can rewrite the Url with NextResponse.rewrite("/denied", request.nextUrl). I think it should work.

    • @hamedbahram
      @hamedbahram  Рік тому

      Yeah that can work, we can rewrite in the `middleware` function.

    • @Hellbending
      @Hellbending 11 місяців тому

      NextJS redirect or router push id imagine?

  • @robertphillips124714
    @robertphillips124714 10 місяців тому +1

    Thanks this was a great explanation, particularly when you explained part of the sequence in which the callbacks run. Any more on that would be super useful.
    Also to take things a step further it would be interesting to see how you would implement authorization in a scenario where you are fetching tailored data according not only to the user's role, but also according to attributes within the data itself. A classic example would be a Todo App, where Admin users see everything, but regular users only get to see Todos that are assigned to them, and Managers only get to see Todos where they are the assigned manager.

    • @hamedbahram
      @hamedbahram  10 місяців тому

      My pleasure! Thanks for the suggestions.

    • @FacundoFalech
      @FacundoFalech 7 місяців тому

      I think you can do it just based the content on the role with useSession() or getServerSession()

  • @rockyessel
    @rockyessel Рік тому +2

    Liked this video, would love to see a video on account linking with next-auth(workaround). But thanks again for the tutorial

    • @hamedbahram
      @hamedbahram  Рік тому

      Sure thing! Can you expand on what you mean by account linking?

    • @rockyessel
      @rockyessel Рік тому

      Okay, let's say a user is already logged, and we want to the user to link to other social media account to connect so maybe for instance we can show that social platform on their profile page. Something like that please.@@hamedbahram

  • @kanodekoubillybrown3025
    @kanodekoubillybrown3025 2 місяці тому

    Thank you for your video , You are teaching developers everyday , How can someone use AuthJs , with a custom backend

    • @hamedbahram
      @hamedbahram  2 місяці тому

      You're welcome. I'll create that video at some point.

  • @haghighi251
    @haghighi251 7 місяців тому +1

    Another great video, Thanks Hamed.

  • @ICOReviewtoken
    @ICOReviewtoken Рік тому +2

    I hope you can make a series of videos about Optimize to increase google speed insight scores. Some common cases include: Fake API from backend, render to Nextjs using swiper slider. Focus on "Eliminate render-blocking resources". This is the most common problem when optimizing. How to asynchronously load CSS while linking CSS files in Nextjs are automatically generated each time you build. If you cannot lazy this CSS and JS file, it will have Eliminate render-blocking resources, affecting LCP and FCP. Thank you bro

    • @hamedbahram
      @hamedbahram  Рік тому +1

      That's such a good idea! I'll definitely work on it. Thanks.

  • @heimdalonline-vp4ho
    @heimdalonline-vp4ho 5 місяців тому +1

    소스코드를 올려주는 당신 너무 좋아요

  • @SajidMunawar-u3w
    @SajidMunawar-u3w 6 місяців тому +2

    how did you assigned role? i mean if user is using google to signin and there are multiple roles and we want user to select one, how we will do that?
    Currently you already have data i.e role in your db so i couldn't understand.
    Thanks in advance

    • @hamedbahram
      @hamedbahram  6 місяців тому

      You can have the admin to assign roles, or an onboarding flow where the user selects the role.

    • @SajidMunawar-u3w
      @SajidMunawar-u3w 6 місяців тому +1

      @@hamedbahram my question is, nextauth handles role based auth so is there a way when we are using nextauth for registering like Google or email providers, at that time we can assign or user can select role?

  • @aleksandarpavlovic2450
    @aleksandarpavlovic2450 Рік тому +1

    very nice tutorial, one question, can user role be automated and changed after user has purchased some plan using stripe for example?

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Yes, absolutely. You can update the user object in your DB and then update the session using the `update` function returned from the `useSession` hook.

  • @linuhusainnk
    @linuhusainnk 2 місяці тому +1

    Is it possible to handle dynamic privileges for different roles

    • @hamedbahram
      @hamedbahram  2 місяці тому

      Can you expand on your question?

  • @tedreams
    @tedreams Рік тому +1

    Awesome work ❤ thanks so much for that. I would like to know if you have a blog where you explain that? Also is it possible to make a video how to reset password combine with something like EmailJs

    • @hamedbahram
      @hamedbahram  Рік тому +1

      Glad to hear that. I don't have a blog version of this video, but I'll write about it at some point. Password reset is a good topic. I'll have that in mind for future videos.

  • @nasko235679
    @nasko235679 5 місяців тому +1

    You kinda skipped over the most important part - how do we implement real-time role changes? This is what I've been stuck on. I've made a nextjs app with latest next auth and it's all great but the issue is the jwt token persist the old user role and even if I change their role if they don't reauthenticate and get a new token it doesn't work. The only way I managed to make it work is by querying the database on each request to compare the db's user role and the session's user role but that doesn't seem scalable at all. This is especially important in apps where you want to ban/deauthorize users in real time. I'm yet to find a guide on how to do it properly without querying the database, if you have any ideas please make a video.

    • @hamedbahram
      @hamedbahram  5 місяців тому

      That'll make a good example usecase. Is it that the user can change their own roles, or and admin changes someone else's role?

    • @nasko235679
      @nasko235679 5 місяців тому

      @@hamedbahram The issue is that once the token gets issued I (as an administrator) can't change the user's role. Well I can, but just because it's changed in the database doesn't mean it's affecting the user because they still have their old token. The obvious issue is that I as an admin can't deauthorize an user on demand. This usually gets solved by providing a "refresher token" along with the jwt token but there is 0 documentation on authjs regarding how to implement refresher tokens with credentials provider. So right now every time a user makes a request I query the database and check their role. Imagine 500k users opening 10-20 pages per minute and what kind of db server load that would create. I can't even schedule the db calls to be let's say once every 5 minutes because NextJS is serverless so it doesn't support it.

  • @alvinpeter1166
    @alvinpeter1166 9 місяців тому +1

    Instead of handling this in the middleware, what if we create a layout component in the admin folder and use the getServerSession to verify if the user is admin else redirect to a 404 page that gives the user a nice error message and a back button. 🤔

    • @hamedbahram
      @hamedbahram  9 місяців тому +1

      That's also a viable solution. Just keep in mind that you can redirect the user to the same page from the middleware. The benefit of the middleware is that it runs on the edge before the request is completed.

  • @md.tofayelislam7591
    @md.tofayelislam7591 10 місяців тому +1

    Plz make one video in complete frontend development roadmap with next.js with projcets idea ❤.❤❤❤. Plz love form Bangladesh 🇧🇩🇧🇩❤

    • @hamedbahram
      @hamedbahram  10 місяців тому

      Absolutely! Thanks for the suggestion.

  • @OpTechMarketing
    @OpTechMarketing Рік тому +2

    Thanks for making this

  • @ayushkathariya
    @ayushkathariya Рік тому +1

    I have created an authentication system in Next.js using NextAuth and protected my route handlers using getServerSessions. However, when I make a fetch request from a client component, my cookies are automatically sent to the backend, and I get authorized. But when I make the same fetch request from a server component, I get unauthorized even I am logged in. Maybe my cookies are not sent automatically . Please reply, why is this happening?

    • @hamedbahram
      @hamedbahram  Рік тому

      You have to pass the headers to your fetch request. First get the `header` from `next/headers` then pass it to your fetch request like:
      ```
      fetch(endpoint, {
      method: "GET",
      headers: headers()
      }
      ```

    • @ayushkathariya
      @ayushkathariya Рік тому +1

      @@hamedbahram Thanks ! It worked.

  • @hafeezullah9706
    @hafeezullah9706 Рік тому +1

    Hi, I am using Laravel APIs with Nextjs, How can I pass authentication bear token to my APIs in Nextjs.(I Just have to protect APIs) Please help me out.

    • @hamedbahram
      @hamedbahram  Рік тому

      You can use the `headers` or `cookies` function from `next/headers`

    • @hafeezullah9706
      @hafeezullah9706 Рік тому

      @@hamedbahram Please make video on ecommerce with Laravel and Nextjs, I do can not find any video about this on youtube.

  • @KSalvatore
    @KSalvatore Рік тому +2

    Hello! Can anyone know the solution for this problem
    Problem: I used google provider in next js. And it is working fine in pc for me. But when I used forward port of vs code to make it possible open website for my friends. But getting error like can't get /api/auth/callback/google
    Please help me

    • @hamedbahram
      @hamedbahram  Рік тому

      You have to update the `NEXTAUTH_URL` env variable and set it to the url you're using to share you project.

    • @KSalvatore
      @KSalvatore Рік тому +1

      @@hamedbahram Thank you very much. It worked. I thought it should change only when in production. Thanks again. Have a good day. And wish you a fortune.

    • @hamedbahram
      @hamedbahram  Рік тому +1

      @@KSalvatore Glad to hear that!

  • @sebastiannietor9724
    @sebastiannietor9724 Рік тому +1

    I need to have another middleware that includes other pages different than the protected, how can I add the other middleware? In another file, the same file?

    • @hamedbahram
      @hamedbahram  Рік тому

      Watch this video => ua-cam.com/video/fmFYH_Xu3d0/v-deo.html

  • @devali-gh
    @devali-gh Рік тому +2

    Hi there. thanks for recording this video. please make another video with nextAuth and make authorization with phoneNumber. in this case from authOptions we use phoneNumber but is session.user i don't have phoneNumber field... because of this, i asked you to record a video for this problem.. thanks :D

    • @hamedbahram
      @hamedbahram  Рік тому

      Sure, I'll have that in mind for future videos.

  • @crysis992
    @crysis992 Рік тому +1

    How would you add this auth middleware to the chain from your chaining middlewares video?

    • @hamedbahram
      @hamedbahram  Рік тому +2

      Good question! you can pass the `middleware` function to the `withAuth` function to run the next middleware. I'll create a video on this combining the `next-auth` middleware and the i18n middleware together this coming week.

    • @nomadmack
      @nomadmack Рік тому +2

      Looking forward for the next video@@hamedbahram. Btw anyway to run a middleware before the auth in withAuth? cause If you run the middleware inside withAuth it will run after it, if I am not mistaken.

    • @hamedbahram
      @hamedbahram  Рік тому

      @@nomadmack That's right it would run after the `authorize` callback. I'll look into that for the video.

    • @any_account-b6x
      @any_account-b6x Рік тому +1

      @@hamedbahram This would be awesome! I'm looking forward to see this video. 😊

    • @hamedbahram
      @hamedbahram  Рік тому +1

      @@any_account-b6x Absolutely!

  • @asimalqasmi7316
    @asimalqasmi7316 Рік тому +2

    Awesome work ❤

  • @siya.abc123
    @siya.abc123 Рік тому +3

    Your content is great sir sometimes I even think you made a mistake making it free 😅
    Thank you for your efforts

  • @rcsbakos2
    @rcsbakos2 Рік тому +1

    Thanks for the video 🇭🇺

  • @thisishabib744
    @thisishabib744 Рік тому +1

    Plz make one video in complete frontend development roadmap with react.js with projcets idea ❤.❤❤❤. Plz love form Bangladesh 🇧🇩🇧🇩❤

    • @hamedbahram
      @hamedbahram  Рік тому +1

      For sure, that a good idea! welcome to the channel.

    • @thisishabib744
      @thisishabib744 Рік тому

      @@hamedbahram waiting for video. I means waiting for a world best front-end development roadmap video. Best of luck hamed ❤️🇧🇩

    • @hamedbahram
      @hamedbahram  Рік тому

      @@thisishabib744 Thanks! I'll try 🤓

  • @siemen_subbaiah
    @siemen_subbaiah 4 місяці тому

    You missed the main part, how to assign users with different roles when doing a google signin?

    • @hamedbahram
      @hamedbahram  4 місяці тому

      That's exactly what I explained in the video.

    • @siemen_subbaiah
      @siemen_subbaiah 4 місяці тому

      ​​@@hamedbahram
      6:46 your saying : "if there is a role on the user object", google does not provide a role property. The only reason you add in your db is because of the Nullish coalescing
      Then you changed the role manually in the Mongo db to admin.
      What everyone wants in is this, this will be the ideal case :
      This is what I'm thinking to implement
      When signing up using Google, by default it'll be user or admin role (depends on your application)
      then using a token in the callback url, decode the token in the signin callback and get the role from a token stored table which has the role column, using this update the user table.
      I don't know if my approach is correct though, couldn't find much resources online to tackle my problem

  • @mehdijafarzade2381
    @mehdijafarzade2381 8 місяців тому +1

    Awesome bro

  • @anversadutt
    @anversadutt Рік тому +1

    awesome always :)

  • @TTT-z2l
    @TTT-z2l Рік тому +3

    I guess the solution closest to the real world would be just hiding the "Admin" menu item.

    • @hamedbahram
      @hamedbahram  Рік тому +3

      That's right! However the user might still try to manually access the `admin` route.