Search code examples
spring-securityintegration-testingkeystorespring-security-oauth2openid-connect

How to configure TestRestTemplate to use a Keystore?


My project has a series of integration tests that use TestRestTemplate and MockMvc. These had been passing successfully.

I have now added Spring Boot Starter Security and Spring Security OAuth2 Autoconfigure dependencies to my project. I have added a custom class that extends WebSecurityConfigurerAdapter to allow open access (for the moment) to my applicaiton. Here is the class

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .authorizeRequests()
            .anyRequest()
            .permitAll();
    }

    @Override
    public void configure(WebSecurity webSecurity) {
        webSecurity
            .ignoring()
            .antMatchers(HttpMethod.OPTIONS, "/**");
    }
}

The application also needs to act as an OAuth2 Resource Server so I have also annotated my main class with @EnableResourceServer. I provide the path to the trusted key store as run parameters when running the application. -Djavax.net.ssl.trustStore=<where the cert is stored locally> -Djavax.net.ssl.trustStorePassword=<the password>

The application works fine but now all of the integration tests are failing. Here is an example of the error common to all the tests that use the TestRestTemplate

Could not fetch user details: class org.springframework.web.client.ResourceAccessException, I/O error on GET request for <the path to my userinfo URL>: 
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: 
unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: 
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

It seems that the TestRestTemplate I am using for my tests needs to be instructed to use the same keystore that the application does. Is it possible to do this? How would it work for MockMvc?


Solution

  • I think you may also need to pass -Djavax.net.ssl.trustStore= -Djavax.net.ssl.trustStorePassword= parameters while running tests. For running single test pass arguments in configuration and in maven also you can pass these parameters.

    Below two links might help

    Specifying trust store information in spring boot application.properties

    http://codeboarding.com/tag/testresttemplate/