Reputation: 359
I'm trying to do integration tests to my Spring-boot app. I have a protected endpoint (/uaa/change_password, Spring MVC), which redirects to /uaa/login when not authenticated. How can I intercept that request I send, I only get back a 200 OK for /uaa/login page. So the test fails for assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
Since the status code is 200. (The other test also fails). Any help appreciated.
Code:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApiAuthServerApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class ApiAuthServerApplicationTests {
@Value("${local.server.port}")
private int port;
private RestTemplate template = new TestRestTemplate();
@Test
public void changePasswordPageProtected() {
ResponseEntity<String> response = template.getForEntity("http://localhost:"
+ port + "/uaa/change_password", String.class);
assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
String auth = response.getHeaders().getFirst("WWW-Authenticate");
assertTrue("Wrong header: " + auth, auth.startsWith("Bearer realm"));
}
}
My config:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin().loginPage("/login").permitAll()
.and()
.requestMatchers().antMatchers(
"/login",
"/oauth/authorize",
"/oauth/confirm_access",
"/reset_password",
"/forgot_password",
"/change_password")
.and()
.authorizeRequests()
.antMatchers("/reset_password", "/forgot_password").permitAll()
.anyRequest().authenticated();
}
Upvotes: 1
Views: 2856
Reputation:
You need to disable automatic redirect in RestTemplate
. I recommend Apache HTTP Client
for that purpose.
Below you'll find an example how to configure RestTemplate
in order to not follow HTTP 302
:
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
....
HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling().build();
new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
Upvotes: 3