Last active
December 30, 2019 04:06
-
-
Save iamitshri/fe93ef8bcac36314416e0e0f4d9869e9 to your computer and use it in GitHub Desktop.
Get Bearer Token And Call a Post Endpoint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package app.service; | |
@Slf4j | |
@Service | |
@RequiredArgsConstructor | |
public class Service { | |
@Autowired | |
private RestTemplate restTemplate; | |
@Value("${security.oauth2.client.client-id}") | |
String clientId; | |
@Value("${security.oauth2.client.client-secret}") | |
String clientSecret; | |
@Value("${security.oauth2.client.access-token-uri}") | |
String tokenUri; | |
@Value("${wgu.hostUrl.url}") | |
private String hostUrl; | |
public void sendUpdates(Model model) { | |
try { | |
String token = getBearerToken(tokenUri, createHttpHeaders(clientId, clientSecret)); | |
callService(token, hostUrl + "/v1/submit", model); | |
} catch (Exception e) { | |
log.error("Error processing update.", e); | |
} | |
} | |
private void callService(@NonNull String bearerToken, @NonNull String hostUrl, | |
@NonNull Model model) { | |
HttpHeaders headers = new HttpHeaders(); | |
headers.add("Authorization", bearerToken); | |
headers.setContentType(MediaType.APPLICATION_JSON); | |
HttpEntity<Model> entity = new HttpEntity<>(model, headers); | |
var result = restTemplate.postForEntity(hostUrl, entity, | |
ResponseEntity.class); | |
log.debug("Status Code:{}", result.getStatusCode()); | |
} | |
private String getBearerToken(String tokenUri, HttpEntity<MultiValueMap<String, String>> headers) { | |
ResponseEntity<PingAccessToken> authToken = | |
restTemplate.exchange(tokenUri, HttpMethod.POST, headers, PingAccessToken.class); | |
var token = authToken.getBody(); | |
String header = token.getTokenType() + " " + token.getAccessToken(); | |
return header; | |
} | |
private HttpEntity<MultiValueMap<String, String>> createHttpHeaders(String clientId, String clientSecret) { | |
HttpHeaders headers = new HttpHeaders(); | |
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); | |
MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); | |
map.add("client_id", clientId); | |
map.add("client_secret", clientSecret); | |
map.add("grant_type", "client_credentials"); | |
return new HttpEntity<>(map, headers); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment