Home > Software design >  Spring Secured Rest Controller is not found in WebMVCTest
Spring Secured Rest Controller is not found in WebMVCTest

Time:11-25

When using @Secured on a REST-Controller, implementing an interface, the Controller is not found in a @WebMvcTest. Either removing the @Secured annotation or removing the implements on the class will make it run in the test.

@Controller
@RequestMapping(path="/failing")
public class FailingTestController implements MyPasswordApi {

    @RequestMapping(method = GET, produces = MediaType.APPLICATION_JSON_VALUE, path = "/test")
    @Secured("ROLE_USER")
    public ResponseEntity<GetEntity> getMethod()

and

@Controller
@RequestMapping(path = "/running")
public class RunningTestController  {

    @RequestMapping(method = GET, produces = MediaType.APPLICATION_JSON_VALUE, path = "/test")
    @Secured("ROLE_USER")
    public ResponseEntity<GetEntity> getMethod() {

are both used in different jUnit-5 Tests. The "RunningTest" will succeed (i.e. the GET-Request will have status 200), whereas the "FailingTest" will end up with a status 404. Using the injected RequestMapppingHanderMapping one can see, that the controller with the inheritance is not bound.

In fact, in the application, both controllers are found.

My question is, how to test an controller implementing security and an interface.

A testcase is found on github: https://github.com/sanddorn/Spring-Boot-Security-Rest-Showcase

CodePudding user response:

The real answer could only be found in the github-repo (see question). The root problem was to annotate the application class with @SpringBootApplication and @EnableGlobalMethodSecurity like

@SpringBootApplication
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class TestApplication {
    public static void main(String []argv) {
        SpringApplication.run(TestApplication.class);
    }
}

Using a different configuration class like

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class TestConfiguration {
}

and removing all extra annotation to the application-class solves the problem.

CodePudding user response:

You are using wrong annotation, replace Controller to RestController

@RestController
@RequestMapping(path = "/running")
public class RunningTestController  {
}
  • Related