I am trying to consume a REST endpoint by using the RestTemplate Library provided by the spring framework. The endpoint also demands a Bearer Access Token as its authorization header, which is only obtained as the response from a user authentication endpoint, which in turn expects an encoded Basic Auth in its Header.
This is the high-level implementation that I have done thus far.
HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setBearerAuth(fetchAccessToken()); HttpEntity<String> entity = new HttpEntity<String>("parameters",headers); ResponseEntity<?> result = this.restClient.exchange(urlToConsume, HttpMethod.GET, entity, String.class);
The 'fetchAccessToken' Method is implemented as follows
HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.setBasicAuth(externalDestination.getClientId(), externalDestination.getClientSecret()); HttpEntity<String> entity = new HttpEntity<String>("parameters", headers); ResponseEntity<?> result = restClient.exchange(authUrl, HttpMethod.GET, entity, String.class); //And Thereby fetching 'access_token' from the successful fetch.
I Want to know whether there is any cleaner way to replicate the above task of dealing with multiple Rest calls to accomplish a single task. Also, I want to know whether I am missing out any essential validations from a security point of view.