Тёмный

Role-based Authentication in NextJs 13 using NextAuth 

Hamed Bahram
Подписаться 120 тыс.
Просмотров 25 тыс.
50% 1

This video will look at implementing role-based access control in NextJs 13 using the NextAuth (Auth.js) library.
👉🏼 The Ultimate NextJs Course
🔗 www.hamedbahram.io/courses/ne...
👉🏼 Project source code (checkout the `role-based-auth` branch)
🔗 github.com/HamedBahram/next-a...
👉🏼 Auth.js documentation
🔗 authjs.dev/guides/basics/role...
👉🏼 Work with me
🔗 www.hamedbahram.io/hire
Chapters
0:00 Intro
1:00 Project setup
3:15 Role-based access control
9:36 Using the middleware
13:10 Outro

Наука

Опубликовано:

 

13 июл 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 73   
@usmansoomro4668
@usmansoomro4668 10 месяцев назад
Sir you are very talented teacher. you followed the different path of teaching web developement.
@hamedbahram
@hamedbahram 10 месяцев назад
Thank you!
@haghighi251
@haghighi251 3 месяца назад
Another great video, Thanks Hamed.
@hamedbahram
@hamedbahram 3 месяца назад
My pleasure!
@asimalqasmi7316
@asimalqasmi7316 10 месяцев назад
Awesome work ❤
@hamedbahram
@hamedbahram 10 месяцев назад
Thanks 😄
@OpTechMarketing
@OpTechMarketing 10 месяцев назад
Thanks for making this
@hamedbahram
@hamedbahram 10 месяцев назад
My pleasure!
@anversadutt
@anversadutt 10 месяцев назад
awesome always :)
@hamedbahram
@hamedbahram 10 месяцев назад
Thank you!
@rcsbakos2
@rcsbakos2 9 месяцев назад
Thanks for the video 🇭🇺
@hamedbahram
@hamedbahram 9 месяцев назад
My pleasure!
@mehdijafarzade2381
@mehdijafarzade2381 5 месяцев назад
Awesome bro
@hamedbahram
@hamedbahram 5 месяцев назад
Appreciate that.
@robertphillips124714
@robertphillips124714 7 месяцев назад
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 7 месяцев назад
My pleasure! Thanks for the suggestions.
@user-jh6xj9st9y
@user-jh6xj9st9y 4 месяца назад
I think you can do it just based the content on the role with useSession() or getServerSession()
@heimdalonline-vp4ho
@heimdalonline-vp4ho 2 месяца назад
소스코드를 올려주는 당신 너무 좋아요
@hamedbahram
@hamedbahram 2 месяца назад
You're welcome!
@rockyessel
@rockyessel 9 месяцев назад
Liked this video, would love to see a video on account linking with next-auth(workaround). But thanks again for the tutorial
@hamedbahram
@hamedbahram 9 месяцев назад
Sure thing! Can you expand on what you mean by account linking?
@rockyessel
@rockyessel 9 месяцев назад
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
@amankch
@amankch 10 месяцев назад
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 10 месяцев назад
Yeah that can work, we can rewrite in the `middleware` function.
@Hellbending
@Hellbending 8 месяцев назад
NextJS redirect or router push id imagine?
@ICOReviewtoken
@ICOReviewtoken 10 месяцев назад
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 10 месяцев назад
That's such a good idea! I'll definitely work on it. Thanks.
@tedreams
@tedreams 10 месяцев назад
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 10 месяцев назад
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.
@aleksandarpavlovic2450
@aleksandarpavlovic2450 9 месяцев назад
very nice tutorial, one question, can user role be automated and changed after user has purchased some plan using stripe for example?
@hamedbahram
@hamedbahram 9 месяцев назад
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.
@buddy.abc123
@buddy.abc123 10 месяцев назад
Your content is great sir sometimes I even think you made a mistake making it free 😅 Thank you for your efforts
@hamedbahram
@hamedbahram 10 месяцев назад
Glad to hear that!
@sebastiannietor9724
@sebastiannietor9724 10 месяцев назад
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 10 месяцев назад
Watch this video => ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-fmFYH_Xu3d0.html
@md.tofayelislam7591
@md.tofayelislam7591 7 месяцев назад
Plz make one video in complete frontend development roadmap with next.js with projcets idea ❤.❤❤❤. Plz love form Bangladesh 🇧🇩🇧🇩❤
@hamedbahram
@hamedbahram 7 месяцев назад
Absolutely! Thanks for the suggestion.
@user-gc3tv6vx7x
@user-gc3tv6vx7x 3 месяца назад
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 3 месяца назад
You can have the admin to assign roles, or an onboarding flow where the user selects the role.
@user-gc3tv6vx7x
@user-gc3tv6vx7x 3 месяца назад
@@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?
@crysis992
@crysis992 10 месяцев назад
How would you add this auth middleware to the chain from your chaining middlewares video?
@hamedbahram
@hamedbahram 10 месяцев назад
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 10 месяцев назад
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 10 месяцев назад
@@nomadmack That's right it would run after the `authorize` callback. I'll look into that for the video.
@fluFFPfizschi
@fluFFPfizschi 10 месяцев назад
@@hamedbahram This would be awesome! I'm looking forward to see this video. 😊
@hamedbahram
@hamedbahram 10 месяцев назад
@@fluFFPfizschi Absolutely!
@devali-gh
@devali-gh 9 месяцев назад
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 9 месяцев назад
Sure, I'll have that in mind for future videos.
@nasko235679
@nasko235679 Месяц назад
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 Месяц назад
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 Месяц назад
@@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 6 месяцев назад
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 6 месяцев назад
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.
@ayushkathariya
@ayushkathariya 9 месяцев назад
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 9 месяцев назад
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 9 месяцев назад
@@hamedbahram Thanks ! It worked.
@thisishabib744
@thisishabib744 10 месяцев назад
Plz make one video in complete frontend development roadmap with react.js with projcets idea ❤.❤❤❤. Plz love form Bangladesh 🇧🇩🇧🇩❤
@hamedbahram
@hamedbahram 10 месяцев назад
For sure, that a good idea! welcome to the channel.
@thisishabib744
@thisishabib744 10 месяцев назад
@@hamedbahram waiting for video. I means waiting for a world best front-end development roadmap video. Best of luck hamed ❤️🇧🇩
@hamedbahram
@hamedbahram 10 месяцев назад
@@thisishabib744 Thanks! I'll try 🤓
@hafeezullah9706
@hafeezullah9706 9 месяцев назад
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 9 месяцев назад
You can use the `headers` or `cookies` function from `next/headers`
@hafeezullah9706
@hafeezullah9706 9 месяцев назад
@@hamedbahram Please make video on ecommerce with Laravel and Nextjs, I do can not find any video about this on youtube.
@KSalvatore
@KSalvatore 9 месяцев назад
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 9 месяцев назад
You have to update the `NEXTAUTH_URL` env variable and set it to the url you're using to share you project.
@KSalvatore
@KSalvatore 9 месяцев назад
@@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 9 месяцев назад
@@KSalvatore Glad to hear that!
@siemen_subbaiah
@siemen_subbaiah Месяц назад
You missed the main part, how to assign users with different roles when doing a google signin?
@hamedbahram
@hamedbahram Месяц назад
That's exactly what I explained in the video.
@siemen_subbaiah
@siemen_subbaiah Месяц назад
​​@@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
@user-cw8lz4ml5u
@user-cw8lz4ml5u 10 месяцев назад
I guess the solution closest to the real world would be just hiding the "Admin" menu item.
@hamedbahram
@hamedbahram 10 месяцев назад
That's right! However the user might still try to manually access the `admin` route.
Далее
Custom Sign-in Emails in NextAuth Using Resend
23:57
Просмотров 11 тыс.
Best father #shorts by Secret Vlog
00:18
Просмотров 17 млн
Nobody Can Do it🚗❓
00:15
Просмотров 6 млн
How Many Balloons Does It Take To Fly?
00:18
Просмотров 77 млн
How I setup role based authorization Next Auth
6:59
Просмотров 10 тыс.
Server-side Pagination with NextJS 13 Server Actions
19:27
Protect Your API - Next Auth Middleware
8:05
Просмотров 33 тыс.
Собери ПК и Получи 10,000₽
1:00
Просмотров 2,5 млн
OZON РАЗБИЛИ 3 КОМПЬЮТЕРА
0:57
Просмотров 1,6 млн