'Java - OAuth 2 using restTemplate to get login with refresh token (StackOverFlowError)

I created an interceptor to get the token before i do other request but i have the error "Method threw 'java.lang.StackOverflowError' exception." when i do the request.

    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
                                        ClientHttpRequestExecution execution) throws IOException {
        request.getHeaders().add("Authorization", "Bearer " + loginWithCredentials());
        return execution.execute(request, body);
    }

    private String loginWithCredentials() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("grant_type", "password");
        map.add("client_id", getClientId());
        map.add("client_secret", getClientSecret());
        map.add("username", getUsername());
        map.add("password", getPassword());

        HttpEntity<String> request = new HttpEntity<>(headers);

        final ResponseEntity<String> responseEntity =  getRestTemplate().exchange(
                getCarrierGatewayTokenUrl(),
                HttpMethod.POST,
                request,
                String.class);

        return responseEntity.getBody();
    } 



Solution 1:[1]

At the risk of you having already figured this out:

Your interceptor runs at calls using restTemplate. Your interceptor makes a call using restTemplate.exchange. So your interceptor calls restTemplate, which runs the interceptor, which calls restTemplate... until your call stack overflows due to recursion.

A way you might avoid this is to skip executing the interceptor if you are calling the carrier gateway token url (using an if-statement), or use a different restTemplate instance without the interceptor.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 timh