Skip to content

Commit

Permalink
fix(http): Close the http client resources in the SDK authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
sbuettner committed Jan 10, 2024
1 parent ede8171 commit 73c9e21
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,23 +53,27 @@ public void resetToken(Product product) {
}

private String retrieveToken(Product product, JwtCredential jwtCredential) {
try {
HttpPost httpPost = new HttpPost(jwtCredential.getAuthUrl());
httpPost.addHeader("Content-Type", "application/json");
TokenRequest tokenRequest = new TokenRequest(jwtCredential.getAudience(), jwtCredential.getClientId(), jwtCredential.getClientSecret());

httpPost.setEntity(new StringEntity(jsonMapper.toJson(tokenRequest)));
CloseableHttpClient client = HttpClient.getInstance();
CloseableHttpResponse response = client.execute(httpPost);
TokenResponse tokenResponse = jsonMapper.fromJson(EntityUtils.toString(response.getEntity()), TokenResponse.class);
tokens.put(product, tokenResponse.getAccessToken());
} catch (Exception e) {
try(CloseableHttpClient client = HttpClient.getInstance()){
HttpPost request = buildRequest(jwtCredential);
TokenResponse tokenResponse = client.execute(request, response ->
jsonMapper.fromJson(EntityUtils.toString(response.getEntity()), TokenResponse.class)
);
tokens.put(product, tokenResponse.getAccessToken());
} catch (Exception e) {
LOG.error("Authenticating for " + product + " failed due to " + e);
throw new RuntimeException("Unable to authenticate", e);
}
return tokens.get(product);
}

private HttpPost buildRequest(JwtCredential jwtCredential) {
HttpPost httpPost = new HttpPost(jwtCredential.getAuthUrl());
httpPost.addHeader("Content-Type", "application/json");
TokenRequest tokenRequest = new TokenRequest(jwtCredential.getAudience(), jwtCredential.getClientId(), jwtCredential.getClientSecret());
httpPost.setEntity(new StringEntity(jsonMapper.toJson(tokenRequest)));
return httpPost;
}

@Override
public Map.Entry<String, String> getTokenHeader(Product product) {
String token;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,35 +81,23 @@ public void resetToken(Product product) {
}

private String retrieveToken(Product product, JwtCredential jwtCredential) {
try {
HttpPost httpPost = new HttpPost(authUrl);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

Map<String, String> parameters = new HashMap<>();
parameters.put("grant_type", "client_credentials");
parameters.put("client_id", jwtCredential.getClientId());
parameters.put("client_secret", jwtCredential.getClientSecret());

String form = parameters.entrySet()
.stream()
.map(e -> {
try {
return e.getKey() + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
})
.collect(Collectors.joining("&"));

httpPost.setEntity(new StringEntity(form));
CloseableHttpClient client = HttpClient.getInstance();
CloseableHttpResponse response = client.execute(httpPost);
TokenResponse tokenResponse;
if (response.getCode() == HttpStatus.SC_OK) {
tokenResponse = jsonMapper.fromJson(EntityUtils.toString(response.getEntity()), TokenResponse.class);
} else {
throw new SdkException("Error "+response.getCode()+" obtaining access token: "+EntityUtils.toString(response.getEntity()));
}
try(CloseableHttpClient client = HttpClient.getInstance()) {
HttpPost request = buildRequest(jwtCredential);
TokenResponse tokenResponse =
client.execute(
request,
response -> {
if (response.getCode() == HttpStatus.SC_OK) {
return jsonMapper.fromJson(
EntityUtils.toString(response.getEntity()), TokenResponse.class);
} else {
throw new SdkException(
"Error "
+ response.getCode()
+ " obtaining access token: "
+ EntityUtils.toString(response.getEntity()));
}
});
tokens.put(product, tokenResponse.getAccessToken());
} catch (Exception e) {
LOG.error("Authenticating for " + product + " failed due to " + e);
Expand All @@ -118,6 +106,31 @@ private String retrieveToken(Product product, JwtCredential jwtCredential) {
return tokens.get(product);
}

private HttpPost buildRequest(JwtCredential jwtCredential) {
HttpPost httpPost = new HttpPost(authUrl);
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

Map<String, String> parameters = new HashMap<>();
parameters.put("grant_type", "client_credentials");
parameters.put("client_id", jwtCredential.getClientId());
parameters.put("client_secret", jwtCredential.getClientSecret());

String form = parameters.entrySet()
.stream()
.map(e -> {
try {
return e.getKey() + "=" + URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8.toString());
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex);
}
})
.collect(Collectors.joining("&"));

httpPost.setEntity(new StringEntity(form));

return httpPost;
}

@Override
public Map.Entry<String, String> getTokenHeader(Product product) {
String token;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,22 +48,20 @@ public Authentication build() {
}

private String retrieveToken(Product product, SimpleCredential simpleCredential) {
try {
HttpPost httpPost = new HttpPost(authUrl);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("username", simpleCredential.getUser()));
params.add(new BasicNameValuePair("password", simpleCredential.getPassword()));
httpPost.setEntity(new UrlEncodedFormEntity(params));

CloseableHttpClient client = HttpClient.getInstance();
CloseableHttpResponse response = client.execute(httpPost);
Header[] cookieHeaders = response.getHeaders("Set-Cookie");
String cookie = null;
for (Header cookieHeader : cookieHeaders) {
if (cookieHeader.getValue().startsWith("OPERATE-SESSION")) {
cookie = response.getHeader("Set-Cookie").getValue();
try(CloseableHttpClient client = HttpClient.getInstance()) {
HttpPost request = buildRequest(simpleCredential);
String cookie = client.execute(request, response -> {
Header[] cookieHeaders = response.getHeaders("Set-Cookie");
String cookieCandidate = null;
String cookiePrefix = product.toString().toUpperCase() + "-SESSION";
for (Header cookieHeader : cookieHeaders) {
if (cookieHeader.getValue().startsWith(cookiePrefix)) {
cookieCandidate = response.getHeader("Set-Cookie").getValue();
break;
}
}
}
return cookieCandidate;
});
if (cookie == null) {
throw new RuntimeException("Unable to authenticate due to missing Set-Cookie");
}
Expand All @@ -75,6 +73,14 @@ private String retrieveToken(Product product, SimpleCredential simpleCredential)
return tokens.get(product);
}

private HttpPost buildRequest(SimpleCredential simpleCredential) {
HttpPost httpPost = new HttpPost(authUrl);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("username", simpleCredential.getUser()));
params.add(new BasicNameValuePair("password", simpleCredential.getPassword()));
httpPost.setEntity(new UrlEncodedFormEntity(params));
return httpPost;
}

@Override
public Map.Entry<String, String> getTokenHeader(Product product) {
Expand Down

0 comments on commit 73c9e21

Please sign in to comment.