|
| 1 | +/* |
| 2 | + * Copyright 2022 AppDynamics Inc. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package io.opentelemetry.contrib.generator.telemetry.transport.auth; |
| 18 | + |
| 19 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 20 | +import com.fasterxml.jackson.databind.JsonNode; |
| 21 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 22 | +import io.opentelemetry.contrib.generator.telemetry.transport.implementations.HTTPClient; |
| 23 | +import lombok.extern.slf4j.Slf4j; |
| 24 | + |
| 25 | +import javax.ws.rs.core.HttpHeaders; |
| 26 | +import java.util.Base64; |
| 27 | +import java.util.Optional; |
| 28 | +import java.util.concurrent.TimeUnit; |
| 29 | + |
| 30 | +/** |
| 31 | + * Class to handle OAuth client credentials workflow which will generate the access token to be used with every request. |
| 32 | + * See <a href="https://www.rfc-editor.org/rfc/rfc6749#section-4.4">OAuth2 Client Credentials specification</a> |
| 33 | + * In case of a different implementation of the OAuth, please use a custom implementation. |
| 34 | + */ |
| 35 | +@Slf4j |
| 36 | +public class OAuthHandler implements AuthHandler { |
| 37 | + |
| 38 | + private final String GET_TOKEN_URL; |
| 39 | + private final String CLIENT_ID; |
| 40 | + private final String CLIENT_SECRET; |
| 41 | + //Provide null for scope if not required |
| 42 | + private final String SCOPE; |
| 43 | + private final HTTPClient httpClient; |
| 44 | + private String accessToken; |
| 45 | + private long expirySeconds; |
| 46 | + |
| 47 | + public OAuthHandler(String GET_TOKEN_URL, String CLIENT_ID, String CLIENT_SECRET, String SCOPE) { |
| 48 | + this.GET_TOKEN_URL = GET_TOKEN_URL; |
| 49 | + this.CLIENT_ID = CLIENT_ID; |
| 50 | + this.CLIENT_SECRET = CLIENT_SECRET; |
| 51 | + this.SCOPE = SCOPE; |
| 52 | + httpClient = new HTTPClient(); |
| 53 | + accessToken = ""; |
| 54 | + expirySeconds = -1; |
| 55 | + } |
| 56 | + |
| 57 | + @Override |
| 58 | + public String getAuthString() { |
| 59 | + if (expirySeconds < TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())) { |
| 60 | + setAccessToken(); |
| 61 | + } |
| 62 | + return "Bearer " + accessToken; |
| 63 | + } |
| 64 | + |
| 65 | + private void setAccessToken() { |
| 66 | + var body = "grant_type=client_credentials"; |
| 67 | + if (SCOPE != null) |
| 68 | + { |
| 69 | + body = body + "&scope=" + SCOPE; |
| 70 | + } |
| 71 | + Optional<String> responseBody = httpClient.postBytes(GET_TOKEN_URL, getHeadersToken(CLIENT_ID, CLIENT_SECRET), body.getBytes()); |
| 72 | + if (responseBody.isEmpty()) { |
| 73 | + log.error("Failed to get fresh token. Post data requests may fail."); |
| 74 | + return; |
| 75 | + } |
| 76 | + extractAndSetToken(responseBody.get()); |
| 77 | + } |
| 78 | + |
| 79 | + private void extractAndSetToken(String tokenSecretResponse) { |
| 80 | + var responseMapper = new ObjectMapper(); |
| 81 | + boolean failure = false; |
| 82 | + JsonNode responseBody = null; |
| 83 | + try { |
| 84 | + responseBody = responseMapper.readTree(tokenSecretResponse); |
| 85 | + } catch (JsonProcessingException e) { |
| 86 | + log.error("Failed to parse json out of token secret response: " + tokenSecretResponse); |
| 87 | + failure = true; |
| 88 | + } |
| 89 | + if (responseBody == null || !responseBody.has("access_token")) { |
| 90 | + log.error("access_token not found in get access token response body: " + tokenSecretResponse); |
| 91 | + failure = true; |
| 92 | + } else { |
| 93 | + accessToken = responseBody.get("access_token").asText(); |
| 94 | + } |
| 95 | + if (responseBody == null || !responseBody.has("expires_in")) { |
| 96 | + log.warn("expires_in field not found in get access token response body: " + tokenSecretResponse); |
| 97 | + log.warn("Will use default expiry time of 60 minutes."); |
| 98 | + } else { |
| 99 | + expirySeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()) + responseBody.get("expires_in").asLong(); |
| 100 | + } |
| 101 | + if (failure) { |
| 102 | + log.error("Failed to get fresh token. Post data requests may fail."); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + private String[] getHeadersToken(String id, String secret) { |
| 107 | + return new String[] {HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=utf-8", |
| 108 | + HttpHeaders.AUTHORIZATION, "Basic " + getEncodedBasicAuth(id, secret)}; |
| 109 | + } |
| 110 | + |
| 111 | + private String getEncodedBasicAuth(String id, String secret) { |
| 112 | + String authStr = id + ":" + secret; |
| 113 | + return Base64.getEncoder().encodeToString(authStr.getBytes()); |
| 114 | + } |
| 115 | + |
| 116 | +} |
0 commit comments