1
1
package com .baeldung .mockjwt .jwtdecoder .junit ;
2
2
3
+ import static org .junit .Assert .assertTrue ;
3
4
import static org .junit .jupiter .api .Assertions .assertEquals ;
4
5
import static org .junit .jupiter .api .Assertions .assertThrows ;
6
+ import static org .mockito .ArgumentMatchers .anyString ;
5
7
import static org .mockito .Mockito .when ;
6
8
7
9
import java .time .Instant ;
10
+ import java .time .temporal .ChronoUnit ;
8
11
import java .util .Arrays ;
9
12
import java .util .HashMap ;
13
+ import java .util .List ;
10
14
import java .util .Map ;
15
+ import java .util .stream .Collectors ;
11
16
12
17
import org .junit .jupiter .api .BeforeEach ;
13
18
import org .junit .jupiter .api .Test ;
14
19
import org .junit .jupiter .api .extension .ExtendWith ;
15
20
import org .mockito .InjectMocks ;
16
21
import org .mockito .Mock ;
17
22
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 ;
18
27
import org .springframework .http .HttpStatus ;
19
28
import org .springframework .http .ResponseEntity ;
29
+ import org .springframework .security .core .GrantedAuthority ;
30
+ import org .springframework .security .core .authority .SimpleGrantedAuthority ;
20
31
import org .springframework .security .core .context .SecurityContextHolder ;
21
32
import org .springframework .security .oauth2 .core .OAuth2Error ;
22
33
import org .springframework .security .oauth2 .jwt .Jwt ;
23
34
import org .springframework .security .oauth2 .jwt .JwtDecoder ;
24
35
import org .springframework .security .oauth2 .jwt .JwtValidationException ;
25
36
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 ;
26
41
27
42
@ ExtendWith (MockitoExtension .class )
28
43
public class MockJwtDecoderJUnitTest {
@@ -70,47 +85,65 @@ void whenTokenHasCustomClaims_thenProcessesCorrectly() {
70
85
.claims (existingClaims -> existingClaims .putAll (claims ))
71
86
.build ();
72
87
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
+
73
96
ResponseEntity <String > response = userController .getUserInfo (jwt );
74
97
75
98
assertEquals ("Hello, john.doe" , response .getBody ());
76
99
assertEquals (HttpStatus .OK , response .getStatusCode ());
100
+
101
+ assertTrue (authentication .getAuthorities ()
102
+ .stream ()
103
+ .anyMatch (auth -> auth .getAuthority ()
104
+ .equals ("ROLE_ADMIN" )));
77
105
}
78
106
79
107
@ Test
80
108
void whenInvalidToken_thenThrowsException () {
81
109
Map <String , Object > claims = new HashMap <>();
82
- claims .put ("sub" , "invalid.user" );
110
+ claims .put ("sub" , null );
83
111
84
112
Jwt invalidJwt = Jwt .withTokenValue ("invalid_token" )
85
113
.header ("alg" , "none" )
86
114
.claims (existingClaims -> existingClaims .putAll (claims ))
87
115
.build ();
88
116
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 );
90
120
91
- JwtValidationException thrown = assertThrows (JwtValidationException .class , () -> jwtDecoder .decode ("invalid_token" ));
121
+ JwtValidationException exception = assertThrows (JwtValidationException .class , () -> {
122
+ userController .getUserInfo (invalidJwt );
123
+ });
92
124
93
- assertEquals ("Invalid token" , thrown .getMessage ());
125
+ assertEquals ("Invalid token" , exception .getMessage ());
94
126
}
95
127
96
128
@ Test
97
- void whenTokenExpired_thenThrowsException () {
129
+ void whenExpiredToken_thenThrowsException () throws Exception {
130
+ // Simulate an expired JWT
98
131
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 ));
104
134
105
135
Jwt expiredJwt = Jwt .withTokenValue ("expired_token" )
106
136
.header ("alg" , "none" )
107
137
.claims (existingClaims -> existingClaims .putAll (claims ))
108
138
.build ();
109
139
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
+ });
113
146
114
- assertEquals ("Token expired" , thrown .getMessage ());
147
+ assertEquals ("Token has expired" , exception .getMessage ());
115
148
}
116
149
}
0 commit comments