use of io.apiman.common.config.options.BasicAuthOptions in project apiman by apiman.
the class HttpApiConnection method connect.
/**
* Connects to the back end system.
*/
private void connect() throws ConnectorException {
try {
String endpoint = ApimanPathUtils.join(api.getEndpoint(), request.getDestination());
if (request.getQueryParams() != null && !request.getQueryParams().isEmpty()) {
// $NON-NLS-1$
String delim = "?";
for (Entry<String, String> entry : request.getQueryParams()) {
endpoint += delim + entry.getKey();
if (entry.getValue() != null) {
// $NON-NLS-1$ //$NON-NLS-2$
endpoint += "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
}
// $NON-NLS-1$
delim = "&";
}
}
URL url = new URL(endpoint);
OkUrlFactory factory = new OkUrlFactory(client);
connection = factory.open(url);
boolean isSsl = connection instanceof HttpsURLConnection;
if (requiredAuthType == RequiredAuthType.MTLS && !isSsl) {
// $NON-NLS-1$
throw new ConnectorException("Mutually authenticating TLS requested, but insecure endpoint protocol was indicated.");
}
if (requiredAuthType == RequiredAuthType.BASIC) {
BasicAuthOptions options = new BasicAuthOptions(api.getEndpointProperties());
if (options.getUsername() != null && options.getPassword() != null) {
if (options.isRequireSSL() && !isSsl) {
// $NON-NLS-1$
throw new ConnectorException("Endpoint security requested (BASIC auth) but endpoint is not secure (SSL).");
}
String up = options.getUsername() + ':' + options.getPassword();
StringBuilder builder = new StringBuilder();
// $NON-NLS-1$
builder.append("Basic ");
builder.append(Base64.encodeBase64String(up.getBytes()));
// $NON-NLS-1$
connection.setRequestProperty("Authorization", builder.toString());
// $NON-NLS-1$
connectorConfig.suppressRequestHeader("Authorization");
}
}
if (hasDataPolicy) {
// $NON-NLS-1$
connectorConfig.suppressRequestHeader("Content-Length");
}
if (isSsl) {
HttpsURLConnection https = (HttpsURLConnection) connection;
SSLSocketFactory socketFactory = sslStrategy.getSocketFactory();
https.setSSLSocketFactory(socketFactory);
https.setHostnameVerifier(sslStrategy.getHostnameVerifier());
}
setConnectTimeout(connection);
setReadTimeout(connection);
if (request.getType().equalsIgnoreCase("PUT") || request.getType().equalsIgnoreCase("POST")) {
// $NON-NLS-1$ //$NON-NLS-2$
connection.setDoOutput(true);
} else {
connection.setDoOutput(false);
}
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(request.getType());
// Set the request headers
for (Entry<String, String> entry : request.getHeaders()) {
String hkey = entry.getKey();
String hval = entry.getValue();
if (!connectorConfig.getSuppressedRequestHeaders().contains(hkey)) {
connection.addRequestProperty(hkey, hval);
}
}
// Set or reset mandatory headers
// $NON-NLS-1$
connection.setRequestProperty("Host", url.getHost() + determinePort(url));
connection.connect();
connected = true;
} catch (IOException error) {
handleConnectionError(error);
}
}
Aggregations