Search code examples
javaspring-bootspring-securityspring-boot-testspring-security-test

Spring Boot: Disable security for Spring Boot Unit Test


Spring Boot version: 2.0.4.RELEASE
For the Spring Boot Test below, the test returns an unwanted 401 response:

"401" status, "error": "unauthorized"

What is the best way to disable Spring Security for the tests?
I tried a adding a configuration "security.basic.enabled=false" property like so:

@SpringBootTest(<br>
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,<br>
    classes = TestApp.class,<br>
    properties = {
        "security.basic.enabled=false"
})

And also adding this annotation to the class:

@AutoConfigureMockMvc(secure = false)

But unfortunately the test still returns a "401" unauthorized error code.

Original test

@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = App.class
)

public class ExampleTest{

@Autowired
public void setup(@LocalServerPort int port) {
    RestAssured.port = port;
}

@Test
public voidtestMethod() {
// This test code is not important to my question.     
given().log().all().get("/resources").then().log().all().statusCode(HttpURLConnection.HTTP_BAD_REQUEST).body("error", equalTo("invalid_request")).body(not(containsString("error_reason")));
}
}

The class being unit tested is simple:

@SpringBootApplication
@RestController
public class App {
@GetMapping("/resources")
public String[] resources(
        @RequestParam("mandatory_param") String mandatory,
        @RequestParam("valid_param") @NotNull String validParam) {
    return new String[]{"1", "2"};
}
...
}

Does anyone know how to disable spring security for the test? Thank you


Solution

  • Using both @SpringBootTest with a random port and @AutoConfiguration might be an issue. Can you try:

    @RunWith(SpringRunner.class)
    @WebMvcTest(App.class)
    @AutoConfigureMockMvc(secure = false)
    public class ExampleTest{}
    

    or

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @EnableAutoConfiguration(exclude = { SecurityAutoConfiguration.class, ManagementSecurityAutoConfiguration.class })
    public class ExampleTest{}
    

    You can event add a custom profile(integration_test) and make:

    security:
          basic:
            enabled: false
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    @ActiveProfiles(value="integration_test")
    public class ExampleTest{}
    

    Update: Just found similar answer already in another SO question : Disable security for unit tests with spring boot