-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathJwtTokenProviderTest.java
More file actions
209 lines (175 loc) · 7.81 KB
/
JwtTokenProviderTest.java
File metadata and controls
209 lines (175 loc) · 7.81 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package com.example.solidconnection.auth.service;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.junit.jupiter.api.Assertions.assertAll;
import com.example.solidconnection.auth.domain.Subject;
import com.example.solidconnection.auth.token.JwtTokenProvider;
import com.example.solidconnection.auth.token.config.JwtProperties;
import com.example.solidconnection.common.exception.CustomException;
import com.example.solidconnection.common.exception.ErrorCode;
import com.example.solidconnection.support.TestContainerSpringBootTest;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.SecretKey;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
@DisplayName("토큰 제공자 테스트")
@TestContainerSpringBootTest
class JwtTokenProviderTest {
@Autowired
private JwtTokenProvider tokenProvider;
@Autowired
private JwtProperties jwtProperties;
private final Subject expectedSubject = new Subject("subject123");
private final Duration expectedExpireTime = Duration.ofMinutes(10);
@Nested
class 토큰을_생성한다 {
@Test
void subject_만_있는_토큰을_생성한다() {
// when
String token = tokenProvider.generateToken(expectedSubject, expectedExpireTime);
// then - subject와 만료 시간이 일치하는지 검증
Subject actualSubject = tokenProvider.parseSubject(token);
Duration actualExpireTime = getActualExpireTime(token);
assertAll(
() -> assertThat(actualSubject).isEqualTo(expectedSubject),
() -> assertThat(actualExpireTime).isEqualTo(expectedExpireTime)
);
}
@Test
void subject_와_claims_가_있는_토큰을_생성한다() {
// given
String key1 = "key1";
String value1 = "value1";
String key2 = "key2";
String value2 = "value2";
Map<String, String> customClaims = Map.of(key1, value1, key2, value2);
// when
String token = tokenProvider.generateToken(expectedSubject, customClaims, expectedExpireTime);
// then - subject와 커스텀 클레임이 일치하는지 검증
Subject actualSubject = tokenProvider.parseSubject(token);
Duration actualExpireTime = getActualExpireTime(token);
assertAll(
() -> assertThat(actualSubject).isEqualTo(expectedSubject),
() -> assertThat(actualExpireTime).isEqualTo(expectedExpireTime),
() -> assertThat(tokenProvider.parseClaims(token, key1, String.class)).isEqualTo(value1),
() -> assertThat(tokenProvider.parseClaims(token, key2, String.class)).isEqualTo(value2)
);
}
private Duration getActualExpireTime(String token) {
Claims claims = Jwts.parser()
.verifyWith(getSigningKey())
.build()
.parseSignedClaims(token)
.getPayload();
return Duration.ofMillis(claims.getExpiration().getTime() - claims.getIssuedAt().getTime());
}
}
@Nested
class 토큰으로부터_subject_를_추출한다 {
@Test
void 유효한_토큰의_subject_를_추출한다() {
// given
String token = tokenProvider.generateToken(expectedSubject, expectedExpireTime);
// when
Subject actualSubject = tokenProvider.parseSubject(token);
// then
assertThat(actualSubject).isEqualTo(expectedSubject);
}
@Test
void 유효하지_않은_토큰의_subject_를_추출하면_예외가_발생한다() {
// given
String subject = "subject123";
String token = createExpiredToken(subject);
// when, then
assertThatCode(() -> tokenProvider.parseSubject(token))
.isInstanceOf(CustomException.class)
.hasMessage(ErrorCode.INVALID_TOKEN.getMessage());
}
@Test
void subject_가_없는_토큰의_subject_를_추출하면_예외가_발생한다() {
// given
String subjectNotExistingToken = createExpiredToken(new HashMap<>());
String subjectBlankToken = tokenProvider.generateToken(new Subject(" "), expectedExpireTime);
// when, then
assertAll(
() -> assertThatCode(() -> tokenProvider.parseSubject(subjectNotExistingToken))
.isInstanceOf(CustomException.class)
.hasMessage(ErrorCode.INVALID_TOKEN.getMessage()),
() -> assertThatCode(() -> tokenProvider.parseSubject(subjectBlankToken))
.isInstanceOf(CustomException.class)
.hasMessage(ErrorCode.INVALID_TOKEN.getMessage())
);
}
}
@Nested
class 토큰으로부터_claim_을_추출한다 {
private final String claimKey = "key";
private final String claimValue = "value";
@Test
void 유효한_토큰의_claim_을_추출한다() {
// given
String token = tokenProvider.generateToken(
expectedSubject,
Map.of(claimKey, claimValue),
expectedExpireTime
);
// when
String actualClaimValue = tokenProvider.parseClaims(token, claimKey, String.class);
// then
assertThat(actualClaimValue).isEqualTo(claimValue);
}
@Test
void 유효하지_않은_토큰의_claim_을_추출하면_예외가_발생한다() {
// given
Map<String, Object> claims = new HashMap<>();
claims.put(claimKey, claimValue);
String token = createExpiredToken(claims);
// when
assertThatCode(() -> tokenProvider.parseClaims(token, claimKey, String.class))
.isInstanceOf(CustomException.class)
.hasMessage(ErrorCode.INVALID_TOKEN.getMessage());
}
@Test
void 존재하지_않는_claim_을_추출하면_null을_반환한다() {
// given
String token = tokenProvider.generateToken(
expectedSubject,
Map.of(claimKey, claimValue),
expectedExpireTime
);
String nonExistentClaimKey = "nonExistentKey";
// when
String actualClaimValue = tokenProvider.parseClaims(token, nonExistentClaimKey, String.class);
// then
assertThat(actualClaimValue).isNull();
}
}
private String createExpiredToken(String subject) {
return Jwts.builder()
.subject(subject)
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() - 1000))
.signWith(getSigningKey())
.compact();
}
private String createExpiredToken(Map<String, Object> claims) {
JwtBuilder builder = Jwts.builder()
.issuedAt(new Date())
.expiration(new Date(System.currentTimeMillis() - 1000));
claims.forEach(builder::claim);
return builder.signWith(getSigningKey()).compact();
}
private SecretKey getSigningKey() {
return Keys.hmacShaKeyFor(jwtProperties.secret().getBytes(StandardCharsets.UTF_8));
}
}