Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid 302 response on https spring security unit test?

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?

like image 822
codemonkey Avatar asked Jan 11 '16 22:01

codemonkey


People also ask

What causes HTTP 302?

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.

What is code 302 in HTTP?

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.

How do I disable spring security for unit testing?

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.


2 Answers

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() )
like image 140
rhinds Avatar answered Oct 27 '22 08:10

rhinds


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();
}
like image 41
codemonkey Avatar answered Oct 27 '22 08:10

codemonkey