Bug 4963: bearer token resolution is now skipped if no username or

password is given
This commit is contained in:
Steffen Schaefer committed 2019-04-03 09:07:34 +02:00
1 parent dba8cb7606
commit 58021d970f
1 file changed
+28 -26
@@ -27,34 +27,36 @@ public final class RemoteServerUtil {
String token = "";
try {
URL base = createBaseUrl(hostname);
String path = "/security/api/restsecurity/access_token";
URL serverAddress = createRemoteServerUrl(base, path, null);
URLConnection connection = HttpUrlConnectionHelper.redirectConnection(serverAddress, Duration.ONE_MINUTE,
t -> {
String auth = username + ":" + password;
String base64 = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
t.setRequestProperty("Authorization", "Basic " + base64);
});
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = connection.getInputStream().read(buffer)) != -1) {
result.write(buffer, 0, length);
}
String jsonToken = result.toString("UTF-8");
Object requestBody = JSONValue.parseWithException(jsonToken);
if (requestBody instanceof JSONObject) {
JSONObject json = (JSONObject) requestBody;
Object tokenObj = json.get("access_token");
if (tokenObj instanceof String) {
token = (String) tokenObj;
logger.info("Obtained access token for user "+username);
if (username != null && !username.isEmpty() && password != null && !password.isEmpty()) {
String path = "/security/api/restsecurity/access_token";
URL serverAddress = createRemoteServerUrl(base, path, null);
URLConnection connection = HttpUrlConnectionHelper.redirectConnection(serverAddress, Duration.ONE_MINUTE,
t -> {
String auth = username + ":" + password;
String base64 = Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8));
t.setRequestProperty("Authorization", "Basic " + base64);
});
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = connection.getInputStream().read(buffer)) != -1) {
result.write(buffer, 0, length);
}
String jsonToken = result.toString("UTF-8");
Object requestBody = JSONValue.parseWithException(jsonToken);
if (requestBody instanceof JSONObject) {
JSONObject json = (JSONObject) requestBody;
Object tokenObj = json.get("access_token");
if (tokenObj instanceof String) {
token = (String) tokenObj;
logger.info("Obtained access token for user "+username);
} else {
logger.warning("Did not find access token for user "+username);
}
} else {
logger.warning("Did not find access token for user "+username);
throw new RuntimeException("Could not obtain token for server");
}
} else {
throw new RuntimeException("Could not obtain token for server");
}
} catch (Exception e) {
throw new RuntimeException(e);