JwtUtilTest.java
2.18 KB
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
56
57
58
59
60
61
62
63
64
package com.xly.erp.common.security;
import com.xly.erp.common.exception.BizException;
import com.xly.erp.common.response.ErrorCode;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
@ActiveProfiles("test")
class JwtUtilTest {
@Autowired
private JwtUtil jwtUtil;
private Map<String, Object> sampleClaims() {
Map<String, Object> claims = new HashMap<>();
claims.put("sub", "42");
claims.put("username", "alice");
claims.put("userType", "NORMAL");
claims.put("companyCode", "HQ");
claims.put("language", "zh-CN");
return claims;
}
@Test
void issuedToken_canBeParsedBackToClaims() {
String token = jwtUtil.issue(sampleClaims(), 7200);
assertNotNull(token);
assertFalse(token.isEmpty());
Map<String, Object> parsed = jwtUtil.parse(token);
assertEquals("42", parsed.get("sub"));
assertEquals("alice", parsed.get("username"));
assertEquals("NORMAL", parsed.get("userType"));
assertEquals("HQ", parsed.get("companyCode"));
assertEquals("zh-CN", parsed.get("language"));
assertNotNull(parsed.get("jti"));
assertNotNull(parsed.get("iat"));
assertNotNull(parsed.get("exp"));
}
@Test
void tamperedToken_throwsBizException() {
String token = jwtUtil.issue(sampleClaims(), 7200);
String tampered = token.substring(0, token.length() - 4) + "XXXX";
BizException e = assertThrows(BizException.class, () -> jwtUtil.parse(tampered));
assertEquals(ErrorCode.BAD_CREDENTIALS, e.getCode());
}
@Test
void expiredToken_throwsBizException() {
String token = jwtUtil.issue(sampleClaims(), 0L);
try { Thread.sleep(1100); } catch (InterruptedException ignored) {}
BizException e = assertThrows(BizException.class, () -> jwtUtil.parse(token));
assertEquals(ErrorCode.BAD_CREDENTIALS, e.getCode());
}
}