feat: make JWT refreshTokens more secure

Don't store the token itself in the database, store a UUID, and when refreshing the accessToken, verify the token and verify that in the payload there is a corresponding UUID stored in the database
This commit is contained in:
Divlo
2022-08-29 17:26:43 +00:00
parent b71da7dcc9
commit 7e305429b4
8 changed files with 75 additions and 37 deletions

View File

@ -1,3 +1,5 @@
import { randomUUID } from 'node:crypto'
import { Type } from '@sinclair/typebox'
import jwt from 'jsonwebtoken'
import ms from 'ms'
@ -34,9 +36,16 @@ export const generateAccessToken = (user: UserJWT): string => {
}
export const generateRefreshToken = async (user: UserJWT): Promise<string> => {
const refreshToken = jwt.sign(user, JWT_REFRESH_SECRET)
const tokenUUID = randomUUID()
const refreshToken = jwt.sign(
{
...user,
tokenUUID
},
JWT_REFRESH_SECRET
)
await prisma.refreshToken.create({
data: { token: refreshToken, userId: user.id }
data: { token: tokenUUID, userId: user.id }
})
return refreshToken
}