0

i want to test my REST Endpoints. In my REST methods are some filters based on the SecurityContext. When i set the SecurityContext in my test classes and call the rest methods, the SecurityContext is deleted. Only when i create the SecurityContext in my REST methods it has an effect. Is there a possibility how to transfer the context?

SecurityContext securityContext = new SecurityContextImpl();
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
    // is here User ...
    .mockMvc.perform(get("/test"...)

RestController:

public ResponseEntity<...> getTest(){
 // is now anonymus
 SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}

thank you

1thingtodo
  • 95
  • 2
  • 15
  • See the answer by Rob Winch: [Run unit tests on controllers that require authentication](http://stackoverflow.com/questions/29704428/) – Ritesh Jan 26 '17 at 17:07
  • You should (almost) never call `SecurityContextHolder` directly in your code. Instead you should just include a parameter of type `Authentication` in your controller method, and Spring will inject it (like it does with `HttpServletRequest/Response`, `Session`, `Model`, and a number of other types) – Klaus Groenbaek Jan 26 '17 at 19:55

1 Answers1

0

You can set an authentication that is re-used for all tests in the same test class using defaultRequest method:

@BeforeClass
public void setUp()
{
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).defaultRequest(get("/").with(authentication(authentication))).apply(springSecurity()).build();
}

The static imports you need are:

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
holmis83
  • 15,922
  • 5
  • 82
  • 83