diff --git a/src/main/java/asia/yulinling/workflow/utils/JwtUtil.java b/src/main/java/asia/yulinling/workflow/utils/JwtUtil.java index b2946bf..872187d 100644 --- a/src/main/java/asia/yulinling/workflow/utils/JwtUtil.java +++ b/src/main/java/asia/yulinling/workflow/utils/JwtUtil.java @@ -103,11 +103,6 @@ public class JwtUtil { // 5. 将token存入redis String redisKey = Const.REDIS_JWT_KEY_PREFIX + username + ":" + userId.toString(); try { - String isPong = null; - if (stringRedisTemplate.getConnectionFactory() != null) { - isPong = stringRedisTemplate.getConnectionFactory().getConnection().ping(); - } - System.out.println("Redis Ping: " + isPong); stringRedisTemplate.opsForValue().set(redisKey, token, ttl, TimeUnit.SECONDS); } catch (RedisException e) { log.error("Redis 写入失败: {}", redisKey, e); @@ -134,12 +129,9 @@ public class JwtUtil { String username = claims.getSubject(); Integer userId = (Integer) claims.get("userId"); - // 2. 获取RedisKey String redisKey = Const.REDIS_JWT_KEY_PREFIX + username + ":" + userId.toString(); - System.out.println("Redis Value: " + stringRedisTemplate.opsForValue().get(redisKey)); - // 3. 校验Token是否存在 Long expire = stringRedisTemplate.getExpire(redisKey, TimeUnit.SECONDS); if (expire <= 0) { @@ -165,7 +157,14 @@ public class JwtUtil { public Long getUserIdByToken(String token) { Claims claims = parseToken(token); - return (Long) claims.get("userId"); + Object userIdObj = claims.get("userId"); + if (userIdObj instanceof Long) { + return (Long) userIdObj; + } else if (userIdObj instanceof Integer) { + return ((Integer) userIdObj).longValue(); + } else { + throw new IllegalArgumentException("Invalid userId type"); + } } public String getUsernameByToken(String token) { @@ -199,7 +198,7 @@ public class JwtUtil { } /** - * 设置Token国企 + * 设置Token过期 * * @param request 请求 */ diff --git a/src/test/java/asia/yulinling/workflow/utils/JwtUtilTest.java b/src/test/java/asia/yulinling/workflow/utils/JwtUtilTest.java index 5f93da8..5ab8c76 100644 --- a/src/test/java/asia/yulinling/workflow/utils/JwtUtilTest.java +++ b/src/test/java/asia/yulinling/workflow/utils/JwtUtilTest.java @@ -10,20 +10,18 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; -import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import java.util.List; +import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.*; -import static org.mockito.ArgumentMatchers.*; -import static org.mockito.Mockito.doNothing; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.when; /** @@ -36,7 +34,6 @@ import static org.mockito.Mockito.when; */ @Slf4j @ExtendWith(MockitoExtension.class) -@SpringBootTest class JwtUtilTest { @Mock private StringRedisTemplate stringRedisTemplate; @@ -44,12 +41,27 @@ class JwtUtilTest { @Mock private ValueOperations valueOps; - @Autowired + @InjectMocks private JwtUtil jwtUtil; @BeforeEach void setUp() { -// when(stringRedisTemplate.opsForValue()).thenReturn(valueOps); + when(stringRedisTemplate.opsForValue()).thenReturn(valueOps); + } + + @Test + public void testGenerateToken() { + // 模拟 UserPrincipal + User user = new User(); + user.setId(100L); + user.setUsername("admin"); + user.setPassword("admin"); + UserDetails userDetails = UserPrincipal.create(user, List.of(), List.of()); + Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null); + // 生成 token + String token = jwtUtil.generateToken(authentication, false); + assertNotNull(token); + assertTrue(token.startsWith("ey")); } @Test @@ -60,89 +72,48 @@ class JwtUtilTest { user.setPassword("admin"); UserDetails userDetails = UserPrincipal.create(user, List.of(), List.of()); Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null); + + when(stringRedisTemplate.getExpire(anyString(), eq(TimeUnit.SECONDS))).thenReturn(60L); + String token = jwtUtil.generateToken(authentication, false); assertNotNull(token); - log.info("Generated Token: {}", token); + when(valueOps.get(anyString())).thenReturn(token); Claims claims = jwtUtil.parseToken(token); - log.info("Parsed Claims: {}", claims); assertEquals("admin", claims.getSubject()); } @Test void testGenerateTokenAndValidateToken() { - - Authentication authentication = new UsernamePasswordAuthenticationToken( - new MockUserPrincipal(100L, "admin", List.of("ADMIN")), - null, - List.of(new SimpleGrantedAuthority("ROLE_ADMIN")) - ); + User user = new User(); + user.setId(100L); + user.setUsername("admin"); + user.setPassword("admin"); + UserDetails userDetails = UserPrincipal.create(user, List.of(), List.of()); + Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null); String token = jwtUtil.generateToken(authentication, false); - System.out.println(token); assertNotNull(token); assertTrue(jwtUtil.validateToken(token)); } -// @Test -// void testValidateToken() { -// UserDetails user = User.withUsername("test") -// .password("test") -// .roles("USER") -// .build(); -// Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()); -// String token = jwtUtil.generateToken(authentication, false); -// assertTrue(jwtUtil.validateToken(token)); -// } - @Test - void testValidateToken2() { - String invalidToken = "this.is.not.valid.jwt"; - assertFalse(jwtUtil.validateToken(invalidToken)); - } - - @Test - void testGenerateTokenFromAuthentication() { - UsernamePasswordAuthenticationToken authentication = - new UsernamePasswordAuthenticationToken( - new MockUserPrincipal(100L, "admin", List.of("ADMIN")), - null, - List.of(new SimpleGrantedAuthority("ROLE_ADMIN")) - ); - + void testGetUserIdByTokenAndGetUsernameByToken() { + User user = new User(); + user.setId(100L); + user.setUsername("admin"); + user.setPassword("admin"); + UserDetails userDetails = UserPrincipal.create(user, List.of(), List.of()); + Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, null); + // 生成 token + when(stringRedisTemplate.getExpire(anyString(), eq(TimeUnit.SECONDS))).thenReturn(60L); String token = jwtUtil.generateToken(authentication, false); assertNotNull(token); + when(valueOps.get(anyString())).thenReturn(token); - Claims claims = jwtUtil.parseToken(token); - assertEquals("admin", claims.getSubject()); - } - - // Mock UserPrincipal 用于测试 - static class MockUserPrincipal extends asia.yulinling.workflow.model.vo.user.UserPrincipal { - private final Long id; - private final String username; - private final List roles; - - public MockUserPrincipal(Long id, String username, List roles) { - super(); // 假设父类有默认构造函数 - this.id = id; - this.username = username; - this.roles = roles; - } - - @Override - public Long getId() { - return id; - } - - @Override - public String getUsername() { - return username; - } - - @Override - public List getRoles() { - return roles; - } + Long userId = jwtUtil.getUserIdByToken(token); + String username = jwtUtil.getUsernameByToken(token); + assertEquals(100L, userId); + assertEquals("admin", username); } }