Skip to content

Commit d1435a3

Browse files
authored
Bael 9146 (#18272)
* BAEL-9146 refine the test case * update the test case
1 parent 62c49b5 commit d1435a3

File tree

2 files changed

+61
-14
lines changed

2 files changed

+61
-14
lines changed

testing-modules/mocks-3/src/test/java/com/baeldung/mockjwt/jwtdecoder/junit/MockJwtDecoderJUnitTest.java

Lines changed: 47 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,43 @@
11
package com.baeldung.mockjwt.jwtdecoder.junit;
22

3+
import static org.junit.Assert.assertTrue;
34
import static org.junit.jupiter.api.Assertions.assertEquals;
45
import static org.junit.jupiter.api.Assertions.assertThrows;
6+
import static org.mockito.ArgumentMatchers.anyString;
57
import static org.mockito.Mockito.when;
68

79
import java.time.Instant;
10+
import java.time.temporal.ChronoUnit;
811
import java.util.Arrays;
912
import java.util.HashMap;
13+
import java.util.List;
1014
import java.util.Map;
15+
import java.util.stream.Collectors;
1116

1217
import org.junit.jupiter.api.BeforeEach;
1318
import org.junit.jupiter.api.Test;
1419
import org.junit.jupiter.api.extension.ExtendWith;
1520
import org.mockito.InjectMocks;
1621
import org.mockito.Mock;
1722
import org.mockito.junit.jupiter.MockitoExtension;
23+
import org.springframework.beans.factory.annotation.Autowired;
24+
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
25+
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
26+
import org.springframework.boot.test.context.SpringBootTest;
1827
import org.springframework.http.HttpStatus;
1928
import org.springframework.http.ResponseEntity;
29+
import org.springframework.security.core.GrantedAuthority;
30+
import org.springframework.security.core.authority.SimpleGrantedAuthority;
2031
import org.springframework.security.core.context.SecurityContextHolder;
2132
import org.springframework.security.oauth2.core.OAuth2Error;
2233
import org.springframework.security.oauth2.jwt.Jwt;
2334
import org.springframework.security.oauth2.jwt.JwtDecoder;
2435
import org.springframework.security.oauth2.jwt.JwtValidationException;
2536
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
37+
import org.springframework.test.web.servlet.MockMvc;
38+
39+
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
40+
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
2641

2742
@ExtendWith(MockitoExtension.class)
2843
public class MockJwtDecoderJUnitTest {
@@ -70,47 +85,65 @@ void whenTokenHasCustomClaims_thenProcessesCorrectly() {
7085
.claims(existingClaims -> existingClaims.putAll(claims))
7186
.build();
7287

88+
List<GrantedAuthority> authorities = ((List<String>) jwt.getClaim("roles")).stream()
89+
.map(role -> new SimpleGrantedAuthority(role))
90+
.collect(Collectors.toList());
91+
92+
JwtAuthenticationToken authentication = new JwtAuthenticationToken(jwt, authorities, jwt.getClaim("sub"));
93+
SecurityContextHolder.getContext()
94+
.setAuthentication(authentication);
95+
7396
ResponseEntity<String> response = userController.getUserInfo(jwt);
7497

7598
assertEquals("Hello, john.doe", response.getBody());
7699
assertEquals(HttpStatus.OK, response.getStatusCode());
100+
101+
assertTrue(authentication.getAuthorities()
102+
.stream()
103+
.anyMatch(auth -> auth.getAuthority()
104+
.equals("ROLE_ADMIN")));
77105
}
78106

79107
@Test
80108
void whenInvalidToken_thenThrowsException() {
81109
Map<String, Object> claims = new HashMap<>();
82-
claims.put("sub", "invalid.user");
110+
claims.put("sub", null);
83111

84112
Jwt invalidJwt = Jwt.withTokenValue("invalid_token")
85113
.header("alg", "none")
86114
.claims(existingClaims -> existingClaims.putAll(claims))
87115
.build();
88116

89-
when(jwtDecoder.decode("invalid_token")).thenThrow(new JwtValidationException("Invalid token", Arrays.asList(new OAuth2Error("invalid_token"))));
117+
JwtAuthenticationToken authentication = new JwtAuthenticationToken(invalidJwt);
118+
SecurityContextHolder.getContext()
119+
.setAuthentication(authentication);
90120

91-
JwtValidationException thrown = assertThrows(JwtValidationException.class, () -> jwtDecoder.decode("invalid_token"));
121+
JwtValidationException exception = assertThrows(JwtValidationException.class, () -> {
122+
userController.getUserInfo(invalidJwt);
123+
});
92124

93-
assertEquals("Invalid token", thrown.getMessage());
125+
assertEquals("Invalid token", exception.getMessage());
94126
}
95127

96128
@Test
97-
void whenTokenExpired_thenThrowsException() {
129+
void whenExpiredToken_thenThrowsException() throws Exception {
130+
// Simulate an expired JWT
98131
Map<String, Object> claims = new HashMap<>();
99-
claims.put("sub", "expired.user");
100-
claims.put("exp", Instant.now()
101-
.minusSeconds(3600));
102-
claims.put("iat", Instant.now()
103-
.minusSeconds(7200));
132+
claims.put("sub", "john.doe");
133+
claims.put("exp", Instant.now().minus(1, ChronoUnit.DAYS));
104134

105135
Jwt expiredJwt = Jwt.withTokenValue("expired_token")
106136
.header("alg", "none")
107137
.claims(existingClaims -> existingClaims.putAll(claims))
108138
.build();
109139

110-
when(jwtDecoder.decode("expired_token")).thenThrow(new JwtValidationException("Token expired", Arrays.asList(new OAuth2Error("invalid_token"))));
111-
112-
JwtValidationException thrown = assertThrows(JwtValidationException.class, () -> jwtDecoder.decode("expired_token"));
140+
JwtAuthenticationToken authentication = new JwtAuthenticationToken(expiredJwt);
141+
SecurityContextHolder.getContext()
142+
.setAuthentication(authentication);
143+
JwtValidationException exception = assertThrows(JwtValidationException.class, () -> {
144+
userController.getUserInfo(expiredJwt);
145+
});
113146

114-
assertEquals("Token expired", thrown.getMessage());
147+
assertEquals("Token has expired", exception.getMessage());
115148
}
116149
}

testing-modules/mocks-3/src/test/java/com/baeldung/mockjwt/jwtdecoder/junit/UserController.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
package com.baeldung.mockjwt.jwtdecoder.junit;
22

3+
import java.time.Instant;
4+
import java.util.Arrays;
5+
36
import org.springframework.http.ResponseEntity;
47
import org.springframework.security.core.annotation.AuthenticationPrincipal;
8+
import org.springframework.security.oauth2.core.OAuth2Error;
59
import org.springframework.security.oauth2.jwt.Jwt;
10+
import org.springframework.security.oauth2.jwt.JwtValidationException;
611
import org.springframework.web.bind.annotation.GetMapping;
712
import org.springframework.web.bind.annotation.RequestMapping;
813
import org.springframework.web.bind.annotation.RestController;
@@ -13,6 +18,15 @@ public class UserController {
1318

1419
@GetMapping("/user")
1520
public ResponseEntity<String> getUserInfo(@AuthenticationPrincipal Jwt jwt) {
21+
if (jwt == null || jwt.getSubject() == null) {
22+
throw new JwtValidationException("Invalid token", Arrays.asList(new OAuth2Error("invalid_token")));
23+
}
24+
25+
Instant expiration = jwt.getExpiresAt();
26+
if (expiration != null && expiration.isBefore(Instant.now())) {
27+
throw new JwtValidationException("Token has expired", Arrays.asList(new OAuth2Error("expired_token")));
28+
}
29+
1630
return ResponseEntity.ok("Hello, " + jwt.getSubject());
1731
}
1832
}

0 commit comments

Comments
 (0)