How do I manage user roles in real time when using NextAuth V5 and jwt tokens?
Unanswered
Order posted this in #help-forum
OrderOP
So I have nextauth v5 set up with credentials and I've set it up so each user has a Role that's an enum of either "USER","BANNED","MOD" or "ADMIN". This role gets passed through the jwt token callback and then it can get checked inside my components to grant/refuse access to each user according to their role. However the problem is that once a jwt token gets issued it belongs to the client and their role gets persisted inside of it. So if I change the role to let's say "BANNED" the user doesn't see the changes until they get issued a new token and they still keep their "USER" access. I'm new to auth and don't know what best practices are to solve this?
1 Reply
OrderOP
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id;
token.username = user.username;
token.role = user.role;
}
return token;
},
async session({ session, token }) {
// Fetch the latest user data every time a session is accessed
const currentUser = await prisma.user.findUnique({
where: {
username: token.username as string,
},
});
console.log(currentUser);
if (currentUser) {
session.user.id = currentUser.id;
session.user.role = currentUser.role;
session.user.username = currentUser.username;
}
return session;
},
},
}); I did this and it does "work" but it's querying the database on every request. Is there a better way?