1

I want to create a Spring boot application, that will call an API through OAuth2 process.

I've already checked this but can some explain it to me in a simple way.

All I have is the URL (that gets the Bearer token), Client ID and Client Secret.

Once the bearer token is retrieved I want to get the call the actual API with the retrieved bearer token put in the header, So I get the response.

James Z
  • 12,209
  • 10
  • 24
  • 44
devguy
  • 81
  • 1
  • 3
  • 10
  • Your question is missing specifics of API you want to call. Which grant type is your API using? If the bearer token you received is an access token then that is sufficient to make an API call. – Sumit Deshmukh Feb 02 '18 at 19:25
  • This tutorial might be useful http://sivatechlab.com/create-rest-client-spring/ – Ahmad Abdelghany Oct 18 '19 at 08:32

1 Answers1

1

In Spring, you can use the RestTemplate.exchange method to make API calls.

Since the API is secured using an OAuth2.0 - Access token (bearer token), the token must be passed in the "Authorization" header.

Try the code shown below to make an API call with header request:

String url = "https://you-api-url";
RestTemplate restTemplate = new RestTemplate();

// set the headers 
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token_value); 

HttpEntity entity = new HttpEntity(headers);

// send the GET request
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);

// display the response
System.out.println("Response" + response.getBody());

Hope it helps!

DwB
  • 37,124
  • 11
  • 56
  • 82
Mohit_Kalra
  • 283
  • 2
  • 12
  • 2
    -1 This is just wrong. You should never send your "client_secret" as a header to the target API. The idea of OAuth is that you use your clientId/secret to request a bearer token. Then you use that bearer token to make the call to the secure API. You need to use OAuth2RestTemplate for that. See https://www.baeldung.com/spring-security-oauth2-authentication-with-reddit or https://stackoverflow.com/questions/27864295/how-to-use-oauth2resttemplate – Ahmad Abdelghany Oct 11 '19 at 10:00