huliguo
2025-05-13 a70919b4f7baab856125f36e5bd41f5ee81be680
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.cl.service.impl;
 
 
import com.cl.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
 
import java.util.Collections;
 
import java.util.Date;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
 
 
@Service
@Slf4j
public class TokenBlacklistService {
    // 使用ConcurrentHashMap或Redis存储黑名单
    private final Set<String> blacklist = Collections.newSetFromMap(new ConcurrentHashMap<>());
 
    public void addToBlacklist(String token) {
        blacklist.add(token);
    }
 
    public boolean isBlacklisted(String token) {
        return blacklist.contains(token);
    }
 
 
    /**
     * 定时清理过期令牌(每2小时执行一次)
     */
    @Scheduled(fixedRate = 2, timeUnit = TimeUnit.HOURS)
    public void cleanupExpiredTokens() {
        log.info("开始清理过期token");
        blacklist.removeIf(this::isTokenExpired);
    }
    /**
     * 检查JWT Token是否过期
     * @param token JWT Token字符串
     * @return true-已过期,false-未过期
     */
    public boolean isTokenExpired(String token) {
        try {
            Claims claims = JwtUtil.parseJWT(token);
            return claims.getExpiration().before(new Date());
        } catch (Exception e) {
            // 如果解析过程中出现异常(如Token无效、已过期等),视为已过期
            return true;
        }
    }
}