-
Notifications
You must be signed in to change notification settings - Fork 0
/
security
37 lines (31 loc) · 1.45 KB
/
security
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
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest // This loads only the web layer with Spring Security configuration
public class SecurityConfigTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testPublicEndpointAccess() throws Exception {
// No authentication required
mockMvc.perform(get("/public/hello"))
.andExpect(status().isOk()); // Public endpoint should return 200 OK
}
@Test
public void testSecuredEndpointAccessWithoutAuthentication() throws Exception {
// No authentication provided
mockMvc.perform(get("/secured"))
.andExpect(status().isUnauthorized()); // Should return 401 Unauthorized
}
@Test
@WithMockUser(username = "user", roles = {"USER"})
public void testSecuredEndpointAccessWithAuthentication() throws Exception {
// Authentication provided via @WithMockUser
mockMvc.perform(get("/secured"))
.andExpect(status().isOk()); // Should return 200 OK for authenticated user
}
}