MockMVC Resets Spring Security Context after each call - spring

I have a custom annotation with a custom filter to authorize incoming requests. The issue is that when I try to test my controllers with MockMvc the Spring Security Context is reset after each use of MockMvc therefore I can only run tests where I only call one endpoint.
Controller:
#RestController
class ElementController {
#RequestMapping(value = ["getElement/{id}"], produces = [APPLICATION_XML_VALUE], method = [GET])
#PreAuthorize("authentication.superUser")
fun getElement(
#PathVariable id: UUID
): String? {
return // call service
}
// For brevity I've removed the other endpoint but it's declaration is similar.
}
Test Class:
#SpringBootTest
#AutoConfigureMockMvc
#ActiveProfiles(INTEGRATION_TESTS)
#DirtiesContext
class ElementTest {
#Autowired
private lateinit var mockMvc: MockMvc
#Test
#WithMockCustomUser(superUser = true) // Custom Annotation created via Spring Docs
fun `Given When Then`() {
// Passes with correct authentication
mockMvc.perform(
put("putElement").content(/*data*/)
).andDo(print()).andExpect(status().isOk)
// Fails because authentication context is empty
val resultGet = mockMvc.perform(
get("getElement/someId")
).andDo(print()).andExpect(status().isOk)
}
}
The above call fails due to org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
I've tried looking through the code and it looks like MockMvc is resetting the security context after every call it makes. I've looked through the docs and it looks like I've set everything up correctly.
I've also looked at this GitHub issue where it's states:
#WithUserDetails will establish the same user for ever request. This is as designed.
Should this mean that my custom annotation should work the same way?
I'd really appreciate the help.
Update:
As a work-around I am setting the Sprint Security Context manually before the second call but I'd like to find a permanent solution.
val authentication = // set authentication
SecurityContextHolder.getContext().authentication = authentication
val resultGet = mockMvc.perform(
get("getElement/someId")
).andDo(print()).andExpect(status().isOk)

Related

Mock SecurityContextHolder / Authentication always returning null

I'm aware this question gets asked a lot, but maybe I have some things that are particular to this. I'm trying to do some integration tests on a Spring Boot application that supports REST (not Spring MVC) and for some reason SecurityContextHolder.getContext().getAuthentication() always returns null, even when using #WithMockUser on the test. I'm not certain if this has to do with using profiles on the configuration classes, but so far we haven't had troubles with this.
Class
#Override
public ResponseEntity<EmployeeDTO> meGet() {
Principal principal = SecurityContextHolder.getContext().getAuthentication();
logger.debug("Endpoint called: me({})", principal);
EmployeeDTO result;
// Get user email from security context
String email = principal.getName(); // NPE here
// ...
}
Test
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = {"eureka.client.enabled:false"})
#WithMockUser
#ActiveProfiles(value = "test")
public class MeControllerTest extends IntegrationSpringBootTest {
#Autowired
private TestRestTemplate restTemplate;
#MockBean
private SecurityContext securityContext;
#MockBean
private Authentication authentication;
#MockBean
private EmployeeRepository employeeRepository;
#BeforeClass
public static void setUp() {
}
#Before
#Override
public void resetMocks() {
reset(employeeRepository);
}
#Test
public void meGet() throws Exception {
when(securityContext.getAuthentication()).thenReturn(authentication);
securityContext.setAuthentication(authentication);
when(authentication.getPrincipal()).thenReturn(mockEmployee());
SecurityContextHolder.setContext(securityContext);
when(employeeRepository.findByEmail(anyString())).thenReturn(mockEmployee());
ResponseEntity<EmployeeDTO> employeeDTOResponseEntity =
this.restTemplate.getForEntity("/me", EmployeeDTO.class);
// ...
}
If I return a mock Principal instead of mockEmployee() the test cannot even start because this happens:
org.springframework.beans.factory.BeanCreationException: Could not inject field: private org.springframework.security.core.Authentication com.gft.employee.controller.MeControllerTest.authentication; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'org.springframework.security.core.Authentication#0' is expected to be of type 'org.springframework.security.core.Authentication' but was actually of type '$java.security.Principal$$EnhancerByMockitoWithCGLIB$$657040e6'
Additional clarifications: This Spring Boot app also uses OAuth2 for authorization, but it must be turned off for these tests. That's why we use profiles. Omitting the #ActiveProfiles annotation gives us a 401 Unauthorized error against the endpoint request.
I could use PowerMock but I would like to avoid it if possible.
Easier Way of writing Junit for Authentication SecurityContextHolder would be to mock them. Following is the working implementation of it.
You can add the mock classes as per your need and then set context of SecurityContextHolder and then use when() to further mock and return proper mock value.
AccessToken mockAccessToken = mock(AccessToken.class);
Authentication authentication = mock(Authentication.class);
SecurityContext securityContext = mock(SecurityContext.class);
when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
when(SecurityContextHolder.getContext().getAuthentication().getDetails()).thenReturn(mockSimpleUserObject);
I ended up using MockMvc despite the app not being Spring MVC-based. Additionally, I separated the SecurityContext calls into another service, but before doing that I could assert that the #WithMockUser annotation was working properly.
What's key for this to work is using these snippets at class level:
#WebMvcTest(MeController.class)
#Import({ControllerConfiguration.class, BeanConfiguration.class})
public class MeControllerTest {
// ...
}
Using #WebMvcTest facilitates not having to initialize a SecurityContext in the first place. You don't even have to call springSecurity(). You can just just the mockMvc.perform() operations as usual, and any calls to the SecurityContext will return whatever mocked user you specify, either with #WithMockUser or mocking the service that handles such a call.
This sample code is working for me. This code is using JUnit 5.
#SpringBootTest(classes = Application.class)
#AutoConfigureMockMvc //need this in Spring Boot test
public class LoginControllerIntegrationTest {
// mockMvc is not #Autowired because I am customizing it #BeforeEach
private MockMvc mockMvc;
#Autowired
private WebApplicationContext context;
#Mock
DefaultOidcUser principal;
#BeforeEach
public void beforeEach() {
Authentication authentication = mock(OAuth2AuthenticationToken.class);
// Mockito.whens() for your authorization object
SecurityContext securityContext = mock(SecurityContext.class);
when(securityContext.getAuthentication()).thenReturn(authentication);
when(authentication.getPrincipal()).thenReturn(principal);
SecurityContextHolder.setContext(securityContext);
// setting mockMvc with custom securityContext
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
#Test
public void given_any_OAuth2AuthenticationToken_when_login_then_redirect_to_logout() throws Exception {
final String loginName = "admin";
// given
// manipulate the principal as needed
when(principal.getAttribute("unique_name")).thenReturn(loginName);
// #formatter:off
// when
this.mockMvc.perform(get("/login"))
.andDo(print())
//then
.andExpect(status().isFound())
.andExpect(redirectedUrl("/logout"));
// #formatter:off
}
}

Mock external server during integration testing with Spring

I have a Spring web server that on a request makes an external call to some third-party web API (e.g. retreive Facebook oauth token). After getting data from this call it computes a response:
#RestController
public class HelloController {
#RequestMapping("/hello_to_facebook")
public String hello_to_facebook() {
// Ask facebook about something
HttpGet httpget = new HttpGet(buildURI("https", "graph.facebook.com", "/oauth/access_token"));
String response = httpClient.execute(httpget).getEntity().toString();
// .. Do something with a response
return response;
}
}
I'm writing an integration test that checks that hitting url on my server leads to some expected result. However I want to mock the external server locally so that I don't even need internet access to test all this. What is the best way to do this?
I'm a novice in spring, this is what I have so far.
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#WebAppConfiguration
#IntegrationTest({})
public class TestHelloControllerIT {
#Test
public void getHelloToFacebook() throws Exception {
String url = new URL("http://localhost:8080/hello_to_facebook").toString();
//Somehow setup facebook server mock ...
//FaceBookServerMock facebookMock = ...
RestTemplate template = new TestRestTemplate();
ResponseEntity<String> response = template.getForEntity(url, String.class);
assertThat(response.getBody(), equalTo("..."));
//Assert that facebook mock got called
//facebookMock.verify();
}
}
The actual real set up is more complicated - I'm making Facebook oauth login and all that logic is not in the controller but in various Spring Security objects. However I suspect that testing code is supposed to be the same since I'm just hitting urls and expect a response, isn't it?
After playing a bit with various scenarios, here is the one way how can one achieve what was asked with minimal interventions to the main code
Refactor your controller to use a parameter for thirdparty server address:
#RestController
public class HelloController {
#Value("${api_host}")
private String apiHost;
#RequestMapping("/hello_to_facebook")
public String hello_to_facebook() {
// Ask facebook about something
HttpGet httpget = new HttpGet(buildURI("http", this.apiHost, "/oauth/access_token"));
String response = httpClient.execute(httpget).getEntity().toString();
// .. Do something with a response
return response + "_PROCESSED";
}
}
'api_host' equals to 'graph.facebook.com' in application.properties in the src/main/resources
Create a new controller in the src/test/java folder that mocks the thirdparty server.
Override 'api_host' for testing to 'localhost'.
Here is the code for steps 2 and 3 in one file for brevity:
#RestController
class FacebookMockController {
#RequestMapping("/oauth/access_token")
public String oauthToken() {
return "TEST_TOKEN";
}
}
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#WebAppConfiguration
#IntegrationTest({"api_host=localhost",})
public class TestHelloControllerIT {
#Test
public void getHelloToFacebook() throws Exception {
String url = new URL("http://localhost:8080/hello_to_facebook").toString();
RestTemplate template = new TestRestTemplate();
ResponseEntity<String> response = template.getForEntity(url, String.class);
assertThat(response.getBody(), equalTo("TEST_TOKEN_PROCESSED"));
// Assert that facebook mock got called:
// for example add flag to mock, get the mock bean, check the flag
}
}
Is there a nicer way to do this? All feedback is appreciated!
P.S. Here are some complications I encountered putting this answer into more realistic app:
Eclipse mixes test and main configuration into classpath so you might screw up your main configuration by test classes and parameters: https://issuetracker.springsource.com/browse/STS-3882 Use gradle bootRun to avoid it
You have to open access to your mocked links in the security config if you have spring security set up. To append to a security config instead of messing with a main configuration config:
#Configuration
#Order(1)
class TestWebSecurityConfig extends WebSecurityConfig {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/oauth/access_token").permitAll();
super.configure(http);
}
}
It is not straightforward to hit https links in integration tests. I end up using TestRestTemplate with custom request factory and configured SSLConnectionSocketFactory.
If you use RestTemplate inside the HelloController you would be able to test it MockRestServiceTest, like here: https://www.baeldung.com/spring-mock-rest-template#using-spring-test
In this case
#RunWith(SpringJUnit4ClassRunner.class)
// Importand we need a working environment
#SpringBootTest(webEnvironment= SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestHelloControllerIT {
#Autowired
private RestTemplate restTemplate;
// Available by default in SpringBootTest env
#Autowired
private TestRestTemplate testRestTemplate;
#Value("${api_host}")
private String apiHost;
private MockRestServiceServer mockServer;
#Before
public void init(){
mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
#Test
public void getHelloToFacebook() throws Exception {
mockServer.expect(ExpectedCount.manyTimes(),
requestTo(buildURI("http", this.apiHost, "/oauth/access_token"))))
.andExpect(method(HttpMethod.POST))
.andRespond(withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body("{\"token\": \"TEST_TOKEN\"}")
);
// You can use relative URI thanks to TestRestTemplate
ResponseEntity<String> response = testRestTemplate.getForEntity("/hello_to_facebook", String.class);
// Do the test you need
}
}
Remember that you need a common RestTemplateConfiguration for autowiring, like this:
#Configuration
public class RestTemplateConfiguration {
/**
* A RestTemplate that compresses requests.
*
* #return RestTemplate
*/
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
And that you have to use it inside HelloController as well
#RestController
public class HelloController {
#Autowired
private RestTemplate restTemplate;
#RequestMapping("/hello_to_facebook")
public String hello_to_facebook() {
String response = restTemplate.getForEntity(buildURI("https", "graph.facebook.com", "/oauth/access_token"), String.class).getBody();
// .. Do something with a response
return response;
}
}
2018 Things have improved much.
I ended up using spring-cloud-contracts
Here's a video introduction https://www.youtube.com/watch?v=JEmpIDiX7LU . The first part of the talk walk you through a legacy service. That's the one you can use for external API.
Gist is,
You create a Contract for the external service using Groovy DSL or other methods that even support explicit calls/proxy or recording. Check documentation on what works for you
Since you dont actually have control over the 3rd party in this case, you will use the contract-verifier and create the stub locally but remember to skipTests
With the stub-jar now compiled and available you can run it from within your test cases as it will run a Wiremock for you.
This question and several stackoverflow answers helped me find the solution so here is my sample project for the next person who has these and other similar microservices related tests.
https://github.com/abshkd/spring-cloud-sample-games
With everything working once you will never ever look back and do all your tests with spring-cloud-contracts
#marcin-grzejszczak the author, is also on SO and he helped a lot figure this out. so if you get stuck, just post on SO.
You could have another spring configuration file that exposes the same endpoint as the HelloController class. You could then simply return the canned json response.
From your code, I'm not sure about just what you are trying to accomplish. If you simply want to see that the call to facebook works then there's no substitute for testing against the service that actually talks to facebook. Mocking the facebook response just to ensure that it is mocked correctly, doesn't strike me as a terribly useful test.
If you are testing to see that the data that comes back from facebook is mutated in some way and you want to make sure that the work being done on it is correct, then you could do that work in a separate method that took the facebook response as a paramater, and then carried out the mutation. You could then check based on various json inputs that it was working correctly.
You could test without bringing the web service into it at all.

Testing a Spring Boot application with custom ErrorAttributes?

I am trying to test a Spring Boot RestController that should use custom error attributes.
#Bean
public ErrorAttributes errorAttributes() {
return new DefaultErrorAttributes() {
#Override
public Map<String, Object> getErrorAttributes(
RequestAttributes requestAttributes,
boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
Throwable error = getError(requestAttributes);
return errorAttributes;
}
};
}
But when i try to test the custom error attributes using a simple test these properties are not taken into account. The test below actually fires a request and i except that the custom attributes are used. But whatever i seem to do the code seems to be not taken into account.
class TestSpec extends Specification {
MockMvc mockMvc
def setup() {
mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build()
}
def "Test simple action"() {
when:
def response = mockMvc.perform(post("/hello")
.contentType(MediaType.APPLICATION_JSON)
.content('{"sayHelloTo": ""}')
)
then:
response.andExpect(status().isOk())
}
}
Any clue on how i could test if the custom attributes?
Spring Boot's error infrastructure works by forwarding requests to an error controller. It's this error controller that uses an ErrorAttributes instance. MockMvc only had fairly basic support for testing the forwarding of requests (you can check that the request would be forwarded, but not the actual outcome of that forward). This means that a MockMvc test that calls your HellowWorldController, either using standalone setup or a web application context-based setup, isn't going to drive the right code path.
A few options:
Unit test your custom ErrorAttributes class directly
Write a MockMvc-based test that calls Spring Boot's BasicErrorController configured with your custom ErrorAttributes instance
Write an integration test that uses RestTemplate to make an actual HTTP call into your service
The test class from Spring gives you a good place to start your own tests!
Create an instance of your custom error attributes class and use MockHttpServletRequest and WebRequest:
private final DefaultErrorAttributes errorAttributes = new YourCustomErrorAttributes();
private final MockHttpServletRequest request = new MockHttpServletRequest();
private final WebRequest webRequest = new ServletWebRequest(this.request);
For your test method:
//Set the appropriate error state in your mocked request object:
RuntimeException ex = new RuntimeException("Test");
this.request.setAttribute("javax.servlet.error.exception", ex);
//Pass the mocked request into the the methods that are normally called by the framework
Map<String, Object> attributes = this.errorAttributes.getErrorAttributes(this.webRequest, ErrorAttributeOptions.of(Include.STACK_TRACE));
// add your own asserts
assertThat(attributes.get("trace").toString()).startsWith("java.lang");

Empty response headers from Spring MockMvc with springSecurityFilterChain

I write unit tests for my Spring MVC application.
This is my mockMvc initialization code:
#Configuration
public class SpringMockFactory {
#Autowired
private WebApplicationContext wac;
#Autowired
private FilterChainProxy springSecurityFilterChain;
#Bean
#Scope("prototype")
public MockMvc getMockMvc() {
return webAppContextSetup(wac)
.addFilter(springSecurityFilterChain)
.build();
}
}
Everything works good, but when I add springSecurityFilterChain response headers are always empty (it's important cause I want to check Set-Cookie header).
I use this code to perform action:
resultActions = mockMvc.perform(post("/api/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.param("username", "sysadmin")
.param("password", "password")
).andDo(print());
And this is the result of andDo(print()):
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body = {"status":200}
Forwarded URL = null
Redirected URL = null
Cookies = []
The question is why are the response headers empty when I use springSecurityFilterChain with mockMvc? And how to read them?
You may need to add Spring security configuration to your MockMvc object.
Example:
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).apply(springSecurity()).build();
The springSecurity() initializer is available in org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers package. You can conveniently static import it.
Note that you need org.springframework.security:spring-security-test dependency (I was good with 4.0.1.RELEASE).
See an example here (didactic project).
I didn't need to manually set a Spring Security filter chain.

Spring 3.0 junit test DispatcherServlet

I am trying to test my application with junit.
Therefore I've setup the following class:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = "/META-INF/spring/applicationContext-test.xml" )
#TransactionConfiguration
#Transactional
public class DispatcherServletTest extends AbstractJUnit4SpringContextTests {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private DispatcherServlet dispatcher;
#Before
public void setUp() throws Exception {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
MockServletConfig config = new MockServletConfig("myapp");
config.addInitParameter("contextConfigLocation","classpath*:webmvc-config.xml");
dispatcher = new DispatcherServlet();
dispatcher.init(config);
}
//test cases
}
So the problem is, that it seems that my dispatcher servlet cannot send any request to any of my controllers.
I think that there is something with the configuration - contextConfigurationLocation.
It looks like he can find the file (otherwise it would throw an exception) , but doesn't load any configuration
The logger says:
org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [http://localhost:8080/myapp/abc]
But I have absolutely no idea what's wrong...
I would appreciate any help!
Thanks in advance
Mines are working fine, try the following tweaks.
if you're using Junit4 no need to extend you test class, the junit runner should do the trick
Load the context config via classpath, and make sure is accessible from the test classpath
#ContextConfiguration(locations={"classpath:applicationContext-test.xml"})
then just test the annotated controllers. I do it like this:
#Test
#Transactional
public void testAnnotatedListUser() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
AnnotationMethodHandlerAdapter handlerAdpt = new AnnotationMethodHandlerAdapter();
request.setRequestURI("/you/URIhere");
ModelAndView mav = handlerAdpt.handle(request, response, this.controller);
assertEquals("Incorrect view name returned", "myexpectedviewname", mav.getViewName());
}
There are several Problems in my question:
At first, it is not possible to extend the AbstractJUnit4SpringContextTests and use #RunWith(...), because it's the same.
At second, you should not use the dispatcherServlert, but an Handler by defining the handler in you application.xml and autowiring it in the test case via #Autowire private Handler handler...
Then everything should work fine!

Resources