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

@ -9,7 +9,7 @@ import {
jwtSchema,
expiresIn
} from '../../../tools/utils/jwtToken.js'
import { UserJWT } from '../../../models/User.js'
import { UserRefreshJWT } from '../../../models/User.js'
import { JWT_REFRESH_SECRET } from '../../../tools/configurations/index.js'
const bodyPostRefreshTokenSchema = Type.Object({
@ -43,20 +43,20 @@ export const postRefreshTokenUser: FastifyPluginAsync = async (fastify) => {
schema: postRefreshTokenSchema,
handler: async (request, reply) => {
const { refreshToken } = request.body
const foundRefreshToken = await prisma.refreshToken.findFirst({
where: { token: refreshToken }
})
if (foundRefreshToken == null) {
throw fastify.httpErrors.forbidden()
}
try {
const userJWT = jwt.verify(
foundRefreshToken.token,
const userRefreshJWT = jwt.verify(
refreshToken,
JWT_REFRESH_SECRET
) as UserJWT
) as UserRefreshJWT
const foundRefreshToken = await prisma.refreshToken.findFirst({
where: { token: userRefreshJWT.tokenUUID }
})
if (foundRefreshToken == null) {
throw fastify.httpErrors.forbidden()
}
const accessToken = generateAccessToken({
id: userJWT.id,
currentStrategy: userJWT.currentStrategy
id: userRefreshJWT.id,
currentStrategy: userRefreshJWT.currentStrategy
})
reply.statusCode = 200
return {