I have a controller like this :
@ExtendWith(SpringExtension.class)
@RestController
@RequestMapping("/")
public class TestController {
@GetMapping(value = "test")
public String test() {
return "Api running";
}
}
I have the following test class:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestController.class)
@AutoConfigureMockMvc
public class TestControllerTest {
private final String BASE_URL = "https://localhost:8080";
@Autowired
private MockMvc mockMvc;
@Test
public void shouldReturnOk() throws Exception{
this.mockMvc.perform(get("/test"))
.andExpect(status().isOk());
}
}
My WebSecurityConfig http configuration looks like this:
@Override
protected void configure(HttpSecurity http) throws Exception {
// Disable CSRF (cross site request forgery)
http.csrf().disable();
// No session will be created or used by spring security
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
// Entry points
http.authorizeRequests()//
.antMatchers("/users/signin").permitAll()//
.antMatchers("/users/signup").permitAll()//
.antMatchers("/h2-console/**/**").permitAll()
.antMatchers("/test").permitAll()
// Disallow everything else..
.anyRequest().authenticated();
// If a user try to access a resource without having enough permissions
http.exceptionHandling().accessDeniedPage("/login");
// Apply JWT
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));
// Optional, if you want to test the API from a browser
// http.httpBasic();
}
When I make an http call from postman the antMatcher
works as it should:
But when I run the test class I get the following response:
java.lang.AssertionError: Status
Expected :200
Actual :401
<Click to see difference>
I'm using intellij IDEA. My folder structure looks like this:
It seems I need to configure the app separately in the tests, but I don't know how that's done.
How do I make my antmatcher allow the request through in the test?
UPDATE: Don't know if it matters but I've noticed that my request is going to a different port than the port I had my app running on:
MockHttpServletRequest:
HTTP Method = GET
Request URI = /test
Parameters = {}
Headers = {}
Body = <no character encoding set>
Session Attrs = {SPRING_SECURITY_SAVED_REQUEST=DefaultSavedRequest[https://localhost:8443/test]}
My app is running on :8080
but it's sending the request to ':8443`. It even does this if I hardcode the url like so: (FURTHER UPDATE: @SimonMartinelli pointed out this is because it's making an https call, so that is not the problem.)
this.mockMvc.perform(get(BASE_URL+ "/test"))
YET ANOTHER UPDATE: it seems it's almost certainly happening because my http.authorizeRequests()
method isn't running. So how do I get it to authorize the requests?