Refresh tokens stored as UUID or JWT?

Viewed 41

I'm creating a refresh token endpoint in my backend using spring boot, and I have a few questions. What's better when creating refresh tokens, should they be a JWT or a simple UUID will suffice?

For example, if I use UUID to generate a refresh token, in my refresh_token table, I would have expiry date, the user who generated that refresh token and of course the random UUID.

public RefreshToken createRefreshToken(Long userId) {
    RefreshToken refreshToken = new RefreshToken();

    refreshToken.setUser(userRepository.findById(userId).get());
    refreshToken.setExpiryDate(Instant.now().plusMillis(refreshTokenDurationMs));
    refreshToken.setToken(UUID.randomUUID().toString());

    refreshToken = refreshTokenRepository.save(refreshToken);
    return refreshToken;
  }

That was my initial implementation, but now I'm thinking isn't it better to create a refresh token as a JWT and have the payload contain the expiry date which mean one less read to the database when validating if a refresh token is not expired? And in the case I store my refresh token jwt, should it be hashed in the database when storing?

Here's a quick method I came up with

private String createRefreshToken(String subject) {
    Instant now = Instant.now();
    JwtClaimsSet claimsSet = JwtClaimsSet.builder()
            .issuer(JWT_ISSUER)
            .issuedAt(now)
            .expiresAt(now.plusSeconds(JWT_REFRESH_TOKEN_EXPIRY))
            .subject(subject)
            .build();

    return jwtEncoder.encode(JwtEncoderParameters.from(claimsSet)).getTokenValue();
}

Which method is better / more secure? Also, maybe a mini question, how can I retrieve the claims expiration when using JWT? I'm using org.springframework.security.oauth2.jwt in my controller?

Thank you!

1 Answers

The purpose of JWT is to store some user details in the token itself so that multiple calls to server could be avoided to get user information like logged in username, permissions etc.

JWT should be used primarily for Access Token as it will be sent back to caller in almost every request.

Refresh Token on the other hand is just a token used to Refresh the access token and doesn't require to be send on every request.

It is better to use a GUID/UUID for Refresh token.

Related