How I setup role based authorization Next Auth

My Products
🏗️ WDC StarterKit: wdcstarterkit.com
📖 ProjectPlannerAI: projectplannerai.com
🤖 IconGeneratorAI: icongeneratorai.com
📝 ThumbnailCritique: thumbnailcritique.com
Useful Links
💬 Discord: / discord
🔔 Newsletter: newsletter.webdevcody.com/
📁 GitHub: github.com/webdevcody
📺 Twitch: / webdevcody
🤖 Website: webdevcody.com
🐦 Twitter: / webdevcody

Пікірлер: 76

  • @reignofrage
    @reignofrage20 күн бұрын

    cody your videos are so informative and helpful. It’s crazy because I open youtube and find one of ur vids that solves an exact problem of mine

  • @EdwardOrnelas
    @EdwardOrnelas20 күн бұрын

    Wow can’t wait for the kit! Multi level auth is something I’ve been needing for a specific project. I’ve been using the tables but this seems far for more streamlined and efficient

  • @sasquatch_devs
    @sasquatch_devs20 күн бұрын

    I've added casl + casl/react on top of this and its a great combo!

  • @marjo9952
    @marjo995220 күн бұрын

    Just in time, ty Cody

  • @complikatd
    @complikatd20 күн бұрын

    killing it every day!

  • @jonathanb.3781
    @jonathanb.37817 күн бұрын

    Thanks for the video. Which add-on are using to display errors directly next to the code?

  • @easylite376
    @easylite37620 күн бұрын

    How do you deal with changes while the user is logged in? So if somebody is changing your role in one group while you are logged in, how do you refresh the information on the token?

  • 20 күн бұрын

    Some logic that let your API know the next time the user makes a request, refresh the token with the updated permissions, etc.

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    UseSession returns an update method you can call which recreates the jwt

  • @easylite376

    @easylite376

    20 күн бұрын

    @@WebDevCody Thank you for your fast answer :) I'm new to frontend and work more in the backend. So if I understand it correctly you can use useSession to update your token on the server. But the following scenario: User A and B are logged in. User B is changing the role of user A in a group. How is the token of user A updated? UseSession cannot update other users token if I understand it correctly?

  • @ParanoicoBR

    @ParanoicoBR

    20 күн бұрын

    @@easylite376 you are correct. One way to mitigate this problem is to call the useSession update method inside the root of your application (assuming you are using a frontend framework). This way, every time the user enters or refresh your webapp it'll update the token. Once the the webapp is loaded, the client side routing will kick in and no other token updates will be made (unless you explicity call the update)

  • @malun22

    @malun22

    18 күн бұрын

    @@easylite376 Id love to know as well :)

  • @PhillipLippi
    @PhillipLippi20 күн бұрын

    I really enjoyed the video! I have a question though: Would it be feasible to create an auxiliary function for data fetching? My concern stems from the fact that for every request, I need to include the authentication token in the header. Consequently, in every page, I find myself having to retrieve the token from the cookie using next/headers. I recall achieving this functionality with Axios and Next.js by setting the token within an Axios variable. Is it possible to replicate this behavior using the Fetch API? OBS: I'm using an external backend application

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    What’s wrong with reading the cookie? A cookie just lives in the request header and it is an in memory operation taking nanoseconds to run.

  • @Dom-zy1qy
    @Dom-zy1qy20 күн бұрын

    Have you ever had to implement quotas? Like, for a subscription system (not pay as you go). Working on setting up something right now where I want the user to be able to perform X operations a month, based on their sub tier. I imagined I could just create a sql query and count the operations the user has performed in the alloted time frame, but that doesn't seem ideal for a few reasons. Maybe I make a "quotas" table with a period_start and period_end column, then deduct their quota? Im using stripe so I could also probably just use the web hook events to update their quota when they renew their sub or it cancels.

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    I did one video about it but I was using a third party gateway service to achieve it.

  • @sakib412
    @sakib41220 күн бұрын

    Informative video. I have a question though. How can I integrate SAAS level i18n support in next js app router. so if user added more than one language they can see the translated route otherwise they will see no lang route by default.

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    I haven’t done i18n before, but I’ll look into that for my starter kit. I think next docs on how to achieve it

  • @sakib412

    @sakib412

    20 күн бұрын

    Thanks, but after introducing app router we need to add manual lang/locale route. before in page router, we just need to add config for i18n. So for default lang we need to add redirect logic so nextjs can also load no lang route. it seems like we are trying to hack that feature.also heard that redirecting locale route is bad for SEO.

  • @raymondmichael4987
    @raymondmichael498720 күн бұрын

    Thanks o Cody, are you using Convex as database in this? I find it really hard to use nextauth with convex database, little help please 😢

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    I’m not, just using Postgres, drizzle, next auth, and next

  • @compton8301
    @compton830120 күн бұрын

    Thanks ❤. Do you prefer Next Auth over Clerk?

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    Clerk is much better. Next auth feels like a hack job at this point, but it’s free 🤷‍♂️

  • @ayukalvieri3154
    @ayukalvieri315418 күн бұрын

    l'm looking to enhance the security of my Next.js app by implementing a feature where users need to re-enter their password before accessing routes displaying sensitive information or performing critical actions. How can I protect these routes to ensure that only authenticated users who have re-entered their password can access them?

  • @diegocarvallo1568
    @diegocarvallo156820 күн бұрын

    Hey Cody - are there any concerns here from a security standpoint? Could a user alter their JWT to a new plan/role ? How do you make sure that these things cant be spoofed/intercepted

  • @Yusuf-ok5rk

    @Yusuf-ok5rk

    20 күн бұрын

    google what a jwt is. jwt itself keeps that from happening cos of how it secures that knowledge with a secret key.

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    no, because the token is signed using a secret that only lives on the backend, so if someone tries to modify the JWT, your server will see it was changed and throw authentication errors

  • @my_yt666

    @my_yt666

    20 күн бұрын

    ​​​@@WebDevCody sure but next-auth exposes update method and api to the client via session provider. I could update my role and plan myself using the provided API. It is a weird default, but you have to explicitly disallow session updates that were triggered initially client-side or at least not let them update critical information.

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    @@my_yt666 wait what? Can you explain a bit more what api you are talking about?

  • @my_yt666

    @my_yt666

    20 күн бұрын

    @@WebDevCody When using useSession hook there is an update method that calls an API. In the JWT callback there is a trigger set to "update". Now notice that you can send anything to the API. You should check the trigger and only update fields that have no critical information. Everything critical should be set during sign in. In v5 there is a new server-side unstable_update.

  • @mattd5419
    @mattd541919 күн бұрын

    How do you refresh a JWT in the case a user is removed or added to a group?

  • @WebDevCody

    @WebDevCody

    19 күн бұрын

    I think you can call const s = useSession(); s.update()

  • @mithatercan
    @mithatercan19 күн бұрын

    Isn't it good to get group membership list and plan in session without adding it to JWT token?

  • @WebDevCody

    @WebDevCody

    19 күн бұрын

    I guess it’s fine as long as the cookie session is encrypted so that the client can’t modify it

  • @codinginflow
    @codinginflow20 күн бұрын

    Have you implemented your own refresh token mechanism to use JWTs in Next-auth?

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    I have not, I assumed it was already built into the library? but now that I see it's not I'm very dissapointed

  • @ExileEditing

    @ExileEditing

    20 күн бұрын

    ​​@@WebDevCody yeah same. You should make a video about it if you get around to it

  • @versaleyoutubevanced8647
    @versaleyoutubevanced864720 күн бұрын

    This useSession got me thinking, it's synchronous, so there is no communication with external system, but still can decode the session. I wonder if it's using a public key to decode a non http only cookie... What's your thoughts on that?

  • @WebDevCody

    @WebDevCody

    19 күн бұрын

    UseSession hits your server to have the server decode the token. If you open the network tab you’ll see it make requests to your api since the browser doesn’t know how to decode the encrypted token

  • @Yahya_Umar
    @Yahya_Umar20 күн бұрын

    Can you please create a stock register app using with multiple role it was really helpful if you could make it.

  • @RaduCiocan
    @RaduCiocan20 күн бұрын

    how do you deal with the case when user create a new group or join a group? You should somehow update the jwt token with the new data.

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    You can call an “update” method from the useSession hook.

  • @luishenriqueandradepellizz680
    @luishenriqueandradepellizz68020 күн бұрын

    Would be wrong to send the access token from Db as a response instead of setting on cookies?

  • @ParanoicoBR

    @ParanoicoBR

    20 күн бұрын

    It's not recommended. The main reason access tokens are sent over cookies (with httpOnly flag enabled) is that client side javascript (malicious and not malicious) won't be able to access it directly. However the user's browser still keep the cookie saved locally and it'll automatically send it to your server on every request, allowing your server to authenticate your users.

  • @luishenriqueandradepellizz680

    @luishenriqueandradepellizz680

    20 күн бұрын

    @@ParanoicoBR but isn’t cookie vulnerable to CSRF attacks?

  • @WebDevCody

    @WebDevCody

    19 күн бұрын

    Yes, you can put refresh token in cookie and access token in memory and set on request headers if you want. If not you need csrf tokens probably

  • @Alex.Shalda
    @Alex.Shalda19 күн бұрын

    in the video I clearly see how you extend the Session object, and it works for me, but could you please explain how you extend the default User object, and the Token object? On my User object there are default properties like id, name, image, email. How do I extend it, so I can grab other properties from my db? Thank you! Very useful video

  • @WebDevCody

    @WebDevCody

    19 күн бұрын

    I just overwrite the global ts types export type User = { id: string; plan: Plan; groupMembershipList: MembershipList; } & DefaultSession["user"]; declare module "next-auth" { // eslint-disable-next-line no-unused-vars interface Session extends DefaultSession { user: User; } }

  • @amosmachoradevlogs
    @amosmachoradevlogs17 күн бұрын

    coincidentally this is like what im doing like right now. Great vid. Here is a video idea. How to use next auth with an external backend. Without nextjs built in backend if you get what im trying to say. because there is this backend guy i work with who built the jwt himself then in my next app i use next-auth so we are really confused on how to amalgamate the two strategies.

  • @liu-river

    @liu-river

    15 күн бұрын

    You don't use next auth in this case, the backend guy sends you the token, you store it in http only cookie and that's it. Then you send the jwt from the client in header in all your request to the backend to verify the user for access control. You should go study how auth work then you will understand what is going on there.

  • @albertilagan
    @albertilagan20 күн бұрын

    What happen if membership/role changes? Will update the token?

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    I think I do need to add logic to force a user to refresh their token if they were to downgrade or upgrade, or get added to a group

  • @neociber24

    @neociber24

    20 күн бұрын

    ​​@@WebDevCody Refreshing JWT is super tricky, specially if you update the role of other user that is already logged. The last time I did this was with websockets to notify the clients they should revalidate, if there is a better way without needing to check each request I want to know it.

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    @@neociber24 from the next-auth docs, it looks like you can just call session.update() from the UI and that will trigger the JWT callback to re-run with an trigger === "update" argument.

  • @domson_0478

    @domson_0478

    20 күн бұрын

    Good informations were exchanged here. And what if user uses multiple devices to log in to the same account. Multiple devices, multiple cookies and you cannot update them because it lives on user device. This is another argument to check everything on request.

  • @qizhang5749

    @qizhang5749

    19 күн бұрын

    Couldn't u keep a socket open and from serverside push a message if the users role changes or their membership revoked then from client-side get refreshed token

  • @esp.luisantonio
    @esp.luisantonio20 күн бұрын

    Congratulations! Is the project open source?

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    Nope this is for a paid starter kit I’m trying to work on

  • @liu-river
    @liu-river15 күн бұрын

    Using JWT, you are very naughty boy.

  • @WebDevCody

    @WebDevCody

    14 күн бұрын

    Living on the edge

  • @amershboul9107
    @amershboul910720 күн бұрын

    can you make a video explain how we manage auth using Redux and Nextjs since my backend guy provides all the auth apis from his side

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    I don't use redux anymore

  • @amershboul9107

    @amershboul9107

    20 күн бұрын

    @@WebDevCody but i believe that if you have a separate BE like my case ,you can't use NextAuth right?

  • @IIllIlIllIlIllIlIlI
    @IIllIlIllIlIllIlIlI20 күн бұрын

    Lessgooo

  • @gerkim3046
    @gerkim304620 күн бұрын

    what about permission based authorization

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    as in fine grained authorization? I'm doing that in this video as well with that list of groups that I put on the JWT

  • @googoochu3923
    @googoochu392320 күн бұрын

    v5 or v4?

  • @WebDevCody

    @WebDevCody

    20 күн бұрын

    I need to check. I may be using 4 but I should migrate. Isn’t 5 still in beta?

  • @googoochu3923

    @googoochu3923

    20 күн бұрын

    @@WebDevCody for next side of auth is stable but for express, sveltkit is still experimental and for others its not even out

  • @CookerSingh
    @CookerSingh20 күн бұрын

    ♥️🤌 he made the video on my most doubtful question.