You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security JWT刷新令牌未过期及存储至用户表字段问题求助

Solutions for Your Spring Boot + Spring Security JWT Refresh Token Issues

Hey there! I’ve tackled similar headaches when working with Spring Security and JWT refresh tokens, so let’s walk through your two issues one by one.

Issue 1: Storing Refresh Tokens in User Database Table & Integrating with Spring Security

Spring Security doesn’t have out-of-the-box automation for tying refresh tokens to a user database table—you’ll need to extend its logic to handle this flow. Here’s a straightforward approach:

  • Update your User Entity: Add fields to store the refresh token and its expiry timestamp:

    @Entity
    public class AppUser {
        // Existing fields like id, username, password, roles...
        private String refreshToken;
        private LocalDateTime refreshTokenExpiry;
    
        // Getters and setters for new fields
    }
    
  • Save Refresh Token on Successful Login: After validating a user’s credentials (either in your custom authentication logic or a AuthenticationSuccessHandler), generate the refresh token and update the user’s database record:

    // Generate refresh token (example uses 7-day expiry)
    String refreshToken = Jwts.builder()
            .setSubject(user.getUsername())
            .setIssuedAt(new Date())
            .setExpiration(new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000))
            .signWith(SignatureAlgorithm.HS512, yourRefreshTokenSecret)
            .compact();
    
    // Update user in database
    user.setRefreshToken(refreshToken);
    user.setRefreshTokenExpiry(LocalDateTime.now().plusDays(7));
    userRepository.save(user);
    
  • Build a Refresh Token Endpoint: Create a POST endpoint (e.g., /api/auth/refresh) that accepts the refresh token, validates it against the database, and returns a new access token:

    @PostMapping("/refresh")
    public ResponseEntity<?> refreshToken(@RequestBody RefreshTokenRequest request) {
        String refreshToken = request.getRefreshToken();
    
        // 1. Parse and validate the refresh token's signature
        Claims claims = Jwts.parser()
                .setSigningKey(yourRefreshTokenSecret)
                .parseClaimsJws(refreshToken)
                .getBody();
    
        // 2. Fetch user from database using the username in the token
        AppUser user = userRepository.findByUsername(claims.getSubject())
                .orElseThrow(() -> new RuntimeException("User not found"));
    
        // 3. Verify the stored refresh token matches and isn't expired
        if (!refreshToken.equals(user.getRefreshToken()) || 
            user.getRefreshTokenExpiry().isBefore(LocalDateTime.now())) {
            throw new RuntimeException("Invalid or expired refresh token");
        }
    
        // 4. Generate new access token
        String newAccessToken = generateAccessToken(user);
    
        return ResponseEntity.ok(new AuthResponse(newAccessToken, refreshToken));
    }
    

Issue 2: Refresh Token Expiry Not Taking Effect

If your refresh token isn’t expiring as expected, check these common missteps:

  • Double-check Expiry Time Calculation: A frequent mistake is using seconds instead of milliseconds when setting the expiration date. Ensure your calculation is correct:

    // Correct: 7 days in milliseconds
    new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000)
    // Wrong: This would expire in 7 hours (missing *1000)
    new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60)
    
  • Validate Expiry During Token Verification: Don’t just verify the token’s signature—make sure you’re checking its expiration date. The JWT parser will throw an exception if the token is expired, but you can also add a manual check:

    if (claims.getExpiration().before(new Date())) {
        throw new RuntimeException("Refresh token has expired");
    }
    
  • Sync Database Expiry with JWT Expiry: If you’re storing the expiry time in the database, ensure it matches the expiration set in the JWT. Mismatched times can lead to tokens being considered valid when they should be expired (or vice versa).

  • Invalidate Old Tokens: When a user gets a new refresh token (e.g., after using the refresh endpoint), always overwrite the old refresh token in the database. This ensures old tokens can’t be reused even if they haven’t expired yet.


内容的提问来源于stack exchange,提问作者Eivyses

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:10:34