JWT callback question
Answered
Lithuanian Hound posted this in #help-forum
Lithuanian HoundOP
Hello. I'm trying to clean my code up a bit, I noticed shadcn's taxonomy uses JWT callback. What's the advantage of using tokens like on the 2nd example?
Shadcn/ui taxonomy project uses this in their auth.ts:
async session({ session, user }) {
try {
const prismaUser = await prisma.user.findUnique({
where: { id: user.id },
});
if (prismaUser) {
session.user = {
...session.user,
id: prismaUser.id,
role: prismaUser.role || UserRole.USER,
};
}
return session;
} catch (error) {
console.error("Session callback error:", error);
throw new Error("Session handling failed");
}
},Shadcn/ui taxonomy project uses this in their auth.ts:
callbacks: {
async session({ token, session }) {
if (token) {
session.user.id = token.id
session.user.name = token.name
session.user.email = token.email
session.user.image = token.picture
}
return session
},
async jwt({ token, user }) {
const dbUser = await db.user.findFirst({
where: {
email: token.email,
},
})
if (!dbUser) {
if (user) {
token.id = user?.id
}
return token
}
return {
id: dbUser.id,
name: dbUser.name,
email: dbUser.email,
picture: dbUser.image,
}
},
},Answered by Jesse
it's more secure to use JWTS and then decoding them instead of just storing it in plain text. It stops people from editing the sessionID as they please to any value, for example if someone finds out another user's ID they could just use it and get access to another user.
3 Replies
it's more secure to use JWTS and then decoding them instead of just storing it in plain text. It stops people from editing the sessionID as they please to any value, for example if someone finds out another user's ID they could just use it and get access to another user.
Answer
@Jesse it's more secure to use JWTS and then decoding them instead of just storing it in plain text. It stops people from editing the sessionID as they please to any value, for example if someone finds out another user's ID they could just use it and get access to another user.
Lithuanian HoundOP
Oh! That's really good to know, is using just openssl rand -base64 32 enough? Except for basic practices to keep jwt safe
You can just use the jsonwebtoken package for creating JWTs