Const
// Standard refresh token validation
const refreshData = {
refreshToken: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
};
const result = RefreshTokenBodySchema.safeParse(refreshData);
if (result.success) {
console.log('Refresh token is valid format');
} else {
console.log('Invalid refresh token:', result.error.errors[0].message);
}
// Token refresh endpoint with validation
router.post('/auth/refresh', validate({ body: RefreshTokenBodySchema }), async (req, res) => {
const { refreshToken } = req.body; // Validated refresh token
try {
const tokenResult = await authService.refreshAccessToken(refreshToken);
res.json({
success: true,
accessToken: tokenResult.accessToken,
refreshToken: tokenResult.newRefreshToken, // Token rotation
expiresIn: tokenResult.expiresIn
});
} catch (error) {
res.status(401).json({ error: 'Invalid or expired refresh token' });
}
});
// Automatic token refresh in client applications
const refreshAccessToken = async (currentRefreshToken: string) => {
const validation = RefreshTokenBodySchema.safeParse({ refreshToken: currentRefreshToken });
if (!validation.success) {
throw new Error('Invalid refresh token format');
}
const response = await fetch('/api/auth/refresh', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(validation.data)
});
if (!response.ok) {
throw new Error('Token refresh failed');
}
return await response.json();
};
// Token validation with expiration checking
const validateAndRefreshToken = async (token: string) => {
// First validate format
const formatValidation = RefreshTokenBodySchema.safeParse({ refreshToken: token });
if (!formatValidation.success) {
throw new ValidationError('Invalid token format');
}
// Then check if token is expired or invalid
try {
const decoded = jwt.verify(token, process.env.REFRESH_TOKEN_SECRET);
return decoded;
} catch (error) {
throw new AuthenticationError('Token expired or invalid');
}
};
JWT refresh token validation schema for token renewal operations
Validation schema for refresh token requests that ensures proper token format and presence before processing token renewal operations. The schema validates that refresh tokens meet minimum length requirements to prevent trivial token guessing attacks while maintaining compatibility with various JWT implementations and token formats.
Refresh tokens are critical security components that allow users to obtain new access tokens without re-authentication, making their validation essential for preventing unauthorized access. The schema ensures tokens are properly formatted and meet minimum security requirements without being overly restrictive about token structure since different JWT libraries may produce tokens of varying lengths.
Security considerations include minimum length validation to prevent brute force attacks against short tokens, string type validation to prevent type confusion attacks, and input sanitization to prevent injection attacks. The schema avoids revealing specific token format requirements that could aid attackers in token forgery attempts.
The validation supports various token renewal flows including automatic token refresh in single-page applications, mobile app token renewal, and server-to-server token refresh operations. It maintains compatibility with different JWT implementations and token rotation strategies used in distributed authentication systems.