1

I have a simple spring boot (1.3.5) app that has a simple integration test that works until I introduce spring-boot-starter-security. I have set in the application.properties the security.user.name and security.user.password which is all I seem to need to password protect my endpoint (and I'd rather not complicate things by adding unnecessary roles or security configs if possible). But now the integration test fails. My test class:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebIntegrationTest(randomPort = true)
public class MyTestsIT {

    private TestRestTemplate template = new TestRestTemplate();
    private URL base;

    @Value("${security.user.name}")
    private String username;

    @Value("${security.user.password}")
    private String password;

    @Value("${local.server.port}")
    private int port;

    @Before
    public void beforeTest() throws MalformedURLException {
        base = new URL("http://" + username + ":" + password + "@localhost:" + port);
    }

    @Test
    public void testHello() throws IllegalStateException, IOException {
        System.err.println(base.toString() + "/hello");
        ResponseEntity<String> response = template.getForEntity(base.toString() + "/hello", String.class);
        assertEquals("Incorrect HTTP status returned", HttpStatus.OK, response.getStatusCode());
        String body = response.getBody();
        assertEquals("Incorrect response string.", "Hello World!", body);
    }
}

The println statement displays the correct url, the same one I've been able to use in curl when I run the app:

curl http://user:password@localhost:8181/hello

The assert for return status is failing with a 401, what am I doing wrong?

CraigFoote
  • 371
  • 1
  • 7
  • 23

2 Answers2

3

D'oh! As soon as I posted my question I found the answer at Basic authentication for REST API using spring restTemplate. Don't know why my searching beforehand didn't hit it. Sorry for the noise and hopefully this will help someone else.

@Before
public void beforeTest() throws MalformedURLException {
    template = new TestRestTemplate(username, password);
    base = new URL("http://localhost:" + port);
}
Community
  • 1
  • 1
CraigFoote
  • 371
  • 1
  • 7
  • 23
0
@Component
public class ServerMockUtils  {

    @Value("${user.name.auth}")
    private String userNameAuth;

    @Value("${password.name.auth}")
    private String passwordNameAuth;

    public MappingBuilder makeMappingBuilderSuccess(MappingBuilder mappingBuilder){

        return mappingBuilder
                .withHeader("Accept", matching("application/json"))
                .withQueryParam("format", equalTo("json"))
                .withBasicAuth(this.userNameAuth, this.passwordNameAuth);
    }
}
public class MockForRestControllerConfig {
    @Autowired
    private ServerMockUtils serverMockUtils;

    @Value("${api.url.external.server}")
    private String apiUrlToExternalServer;

    public void setupStubForProcessingRequest(int portExternalServerMock) {

        String addressHost = "127.0.0.1";

        configureFor(addressHost, portExternalServerMock);

        setupResponseInCaseSuccessProcessingRequest();
    }



    private void setupResponseInCaseSuccessProcessingRequest(){

          UrlPathPattern urlPathPattern = urlPathEqualTo(this.apiUrlToExternalServer);

        MappingBuilder mappingBuilder = get(urlPathPattern);

        MappingBuilder mappingBuilderWithHeader = serverMockUtils.makeMappingBuilderSuccess(mappingBuilder);

        int statusOk = HttpStatus.OK.value();

        ResponseDefinitionBuilder responseDefinitionBuilder = aResponse().
                withStatus(statusOk)
                .withHeader("Content-Type", "application/json")
                .withBodyFile("json/json.json");

        MappingBuilder responseForReturn = mappingBuilderWithHeader.willReturn(responseDefinitionBuilder);

        stubFor(responseForReturn);
    }

}
    public ResponseEntity<ExternalServerDto> sendRequestToExternalServer(int portExternalServerMock) {

        String fullUrlToExternalServer = makeFullUrlToExternalServer(portExternalServerMock);
        UriComponentsBuilder uriComponentsBuilder = buildUriToExternalServer(fullUrlToExternalServer);
        String uriWithParamsToExternalServer = uriComponentsBuilder.toUriString();

        HttpHeaders requestHttpHeaders = getHeadersHttpHeaders();
        HttpEntity<Object> requestHttpEntity = new HttpEntity<>(null, requestHttpHeaders);

        return testRestTemplate.exchange(
                uriWithParamsToExternalServer,
                HttpMethod.GET,
                requestHttpEntity,
                ExternalServerDto.class
        );
    }

    private String makeFullUrlToExternalServer(int portExternalServerMock) {

        String prefixUrlToExternalServer = "http://127.0.0.1:";
        return prefixUrlToExternalServer +
                portExternalServerMock +
                this.apiUrlToExternalServer;

    }

    private HttpHeaders getHeadersHttpHeaders() {

        var requestHttpHeaders = new HttpHeaders();
        requestHttpHeaders.add("Accept", MediaType.APPLICATION_JSON_VALUE);
        addBasicAuth(requestHttpHeaders);

        return requestHttpHeaders;
    }

    private UriComponentsBuilder buildUriToExternalServer(String urlToExternalServer) {

        return UriComponentsBuilder.fromHttpUrl(urlToExternalServer)
                .queryParam("format", "json")
    }

    private void addBasicAuth(HttpHeaders httpHeaders) {

        String auth = this.userNameAuth + ":" + this.passwordNameAuth;

        byte[] encodedAuth = Base64.encodeBase64(
                auth.getBytes(StandardCharsets.US_ASCII));

        String authHeader = "Basic " + new String(encodedAuth);

        httpHeaders.add("Authorization", authHeader);

    }
  • pom.xml
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>com.jayway.jsonpath</groupId>
                    <artifactId>json-path</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>com.github.tomakehurst</groupId>
            <artifactId>wiremock</artifactId>
            <version>2.27.2</version>
            <scope>test</scope>
        </dependency>
skyho
  • 1,438
  • 2
  • 20
  • 47