I've got java Spring Security app (built with jhipster) and I'm trying to add some unit tests that test logic based on the current authenticated user.
To do that i've configured my MockMvc
object to use a web application context and spring security as so:
@Test
@Transactional
public void getAllContacts() throws Exception {
restContactMockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
restContactMockMvc.perform(get("/api/contacts")).andExpect(status().isOk());
}
The problem is that I've also configured the app to require HTTPS, and whenever I run this unit test I get a 302 redirect response since it appears to be trying to send an HTTP request instead of HTTPS.
The way I've enforced HTTPS is with the following line in SecurityConfiguration.configure(HttpSecurity http)
:
if (env.acceptsProfiles("!dev"))http.requiresChannel().anyRequest().requiresSecure();
So, my question is how can I get my unit test to run correctly? Probably either by sending a mock HTTPS request, or by disabling HTTPS in the case of running a unit test?
What is an HTTP 302? The 302 status code is a redirection message that occurs when a resource or page you're attempting to load has been temporarily moved to a different location.
The HyperText Transfer Protocol (HTTP) 302 Found redirect status response code indicates that the resource requested has been temporarily moved to the URL given by the Location header.
One of the ways you can disable Spring Security filters in your tests, is to use the @AutoConfigureMockMvc annotation. @AutoConfigureMockMvc annotation can be applied to a test class to enable and configure auto-configuration of MockMvc.
Using Springs MockMvc stuff you can also specify that you want to send a mock HTTPS request using the secure(true) method as follows:
restContactMockMvc.perform( get("/api/contacts").secure( true ) ).andExpect( status().isOk() )
I'm answering my own question with the fix that i've started using, in hopes that this can help others. I'm still open to other better solutions.
In SecurityConfiguration.configure(HttpSecurity http)
method, i've modified the if statement for enforcing https to skip it if we are running an integrationTest:
if (env.acceptsProfiles("!dev") && !((StandardEnvironment) env).getPropertySources().contains("integrationTest")) {
http.requiresChannel().anyRequest().requiresSecure();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With