I need to recover a token from amazon cognito service. I tried to use Spring RestTemplate, but when I request the URL in Java I got the following error:
org.springframework.web.client.HttpClientErrorException$MethodNotAllowed: 405 Method Not Allowed: [no body]
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:117)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:186)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:125)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:819)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:711)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:602)
Below is my code (okay compagny and aHash were removed for this ticket):
Map<String, String> params = new LinkedHashMap<>();
params.put("grant_type", "client_credentials");
// build the url with params
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("https://company.auth.eu-west-1.amazoncognito.com/oauth2/token");
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.queryParam(entry.getKey(), entry.getValue());
}
Map<String, String> headers = new LinkedHashMap<>();
headers.put(AUTHORIZATION, "Basic aHash==");
headers.put("Content-Type", "application/x-www-form-urlencoded");
log.error("GenerateRemoteTokenURI requesting: {}", builder.toUriString());
HttpEntity<String> tokenResponseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, new HttpEntity<>(headers),
String.class);
If I use a curl with that:
curl --location --request POST 'https://company.eu-west-1.amazoncognito.com/oauth2/token?grant_type=client_credentials' \ [14:28:53]
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Authorization: Basic aHash=='
I got my access_token without any problem.
Do you know why I got this error from Spring, and how I can resolve the problem, please?
Thank you a lot and best regards