Tuesday, 20 February 2018

Calling SSL Based Web Service Client Using Apache DefaultHttpClient

final DefaultHttpClient defaultHttpClient = getDefaultHttpClient();
final URIBuilder builder = new URIBuilder();
builder.setPath(url).setParameter(a, val)

final URI uri = builder.build();
final HttpPost request = new HttpPost(uri);

request.addHeader(Accept-Encoding, gzip,deflate);
request.addHeader(Content-Type, application/x-www-form-urlencoded);
--request.addHeader(HOST, HOST_VALUE);
request.addHeader(Keep-Alive, CONNECTION_VALUE);
request.addHeader(User-Agent, Apache-HttpClient/4.1.1);
HttpResponse response = defaultHttpClient.execute(request);

if (response.getStatusLine().getStatusCode() == HttpStatusCodes.OK.getStatusCode()) {
return processDemoResponse(response);
}

} else if (response.getStatusLine().getStatusCode() == HttpStatusCodes.INTERNAL_SERVER_ERROR.getStatusCode()) {
// error handle
}

private String processDemoResponse(final HttpResponse response) {

HttpEntity entity = response.getEntity();
final Header contentEncodingHeader = entity.getContentEncoding();

if (contentEncodingHeader != null) {
final HeaderElement[] encodings = contentEncodingHeader.getElements();
for (int i = 0; i < encodings.length; i++) {
if (GZIP.equalsIgnoreCase(encodings[i].getName())) {
entity = new GzipDecompressingEntity(entity);
break;
}
}
}

final DemoResponse demoResponse = new ObjectMapper().readValue(
EntityUtils.toString(entity, Charset.forName(UTF-8).name()), DemoResponse.class);

return demoResponse.getAccessToken();
}


@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class DemoResponse {
@JsonProperty("token_type")
private String tokentype;
@JsonProperty("expires_in")
private String expiresin;
@JsonProperty("error")
private String error;
@JsonProperty("error_description")
private String errordescription;
}

void getDefaultHttpClient()
{
DefaultHttpClient defaultHttpClient = null;
try {
SSLContext sslContext = null;
// To initialise keyStore, we need default keystore.
final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
// Key manage factory
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
// trust key store
keyManagerFactory.init(ks, null);

final KeyStore trustKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
// load trustKeyStore

final TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustKeyStore);

sslContext = SSLContext.getInstance("TLS);
final X509TrustManager tm = overrideTrustManager();
sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { tm }, null);
final org.apache.http.conn.ssl.SSLSocketFactory ssf = new org.apache.http.conn.ssl.SSLSocketFactory(sslContext);
final HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 20000);
defaultHttpClient = new DefaultHttpClient(httpParams);

final ClientConnectionManager ccm = defaultHttpClient.getConnectionManager();
final SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme(https, 443, ssf));
}

public static X509TrustManager overrideTrustManager() {

return new X509TrustManager() {
@Override
public void checkClientTrusted(final java.security.cert.X509Certificate[] arg0, final String arg1)
throws CertificateException {
// Do Nothing
}

@Override
public void checkServerTrusted(final java.security.cert.X509Certificate[] arg0, final String arg1)
throws CertificateException {
// Do Nothing
}

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
};
}


-----------------------
Configuring Certificates:

sudo to ofmmgr user using: /opt/sfw/bin/sudo -u ofmmgr -i

cd “/app/oracle/domains/keys”

Copy the certificate into “/app/oracle/domains/keys” . certificates can be downloaded from below URL for test environment. Also available in release certificate folder.
URL: https://demo:8443/d/ddd?wsdl

Run below command to list the certificates

For Dev, Test & PT use below
keytool -list -keystore DemoTrust.jks -storepass DemoTrustKeyStorePassPhrase (PassPhrase is based on environment - This step is only for DEV & TEST)

Sample Outcome:

The above command will list below certificates:

Keystore type: JKS

Keystore provider: SUN

Your keystore contains 4 entries

6. Importing Remedy certificate using below commands.

keytool -import -v -trustcacerts -alias -keypass -storepass -file "" -keystore DemoTrust.jks (ONLY FOR DEV, TEST & PT)

For Example as below: (For Dev, Test & PT).

keytool -import -v -trustcacerts -alias DemoCertificate -keypass changeit -storepass DemoTrustKeyStorePassPhrase -file "Demo.cer" -keystore DemoTrust.jks

It will ask for confirmation enter ‘yes’ and then enter; that’s all that will import the certificate.

keytool -importcert -file -alias -keystore -storepass (For Pre-Prod, Post-Prod & PROD)

For Example:

keytool -importcert -file DemoCertificate.cer -alias DemoCertificate -keystore Trust.jks -storepass

Sample Outcome from command prompt:


Trust this certificate? [no]: yes

Certificate was added to keystore

[Storing DemoTrust.jks]

7. And now to see use list command to list down the imported certificates as below:

keytool -list -keystore DemoTrust.jks -storepass DemoTrustKeyStorePassPhrase (Only for DEV & TEST)

Now you can see the last one which we had imported is shown.


Keystore type: JKS

Keystore provider: SUN


Your keystore contains 5 entries


8. Restart the SSL

a. Login into Admin Console.

b. Navigate to Environment > Servers > WLS_SRV7 > Control (TAB) > Restart SSL

c. Follow the step b and restart the SSL for WLS_SRV8.

For SSL Handshake calling other webservices

public void configureSSLHandshake(final BindingProvider port, final String sender, final String userId) throws IOException {

SSLContext sslContext = null;
FileInputStream fileInputStream = null;

try {
final KeyStore keyStoreTrustManagerFactory = KeyStore.getInstance(KeyStore.getDefaultType());
fileInputStream = new FileInputStream(TRUST_STORE_LOCATION));

keyStoreTrustManagerFactory.load(fileInputStream, getSecurity().toCharArray());

final TrustManagerFactory trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStoreTrustManagerFactory);

sslContext = SSLContext.getInstance("TLS");
final X509TrustManager tm = overrideTrustManager();
sslContext.init(null, new TrustManager[] { tm }, null);
} catch (final Exception e) {
LOGGER.error("Error configuring SSL handshake information", e);
} finally {
if (null != fileInputStream) {
fileInputStream.close();

}
}
port.getRequestContext().put("com.sun.xml.ws.transport.https.client.SSLSocketFactory", sslContext.getSocketFactory());

}

private X509TrustManager overrideTrustManager() {

return new X509TrustManager() {
@Override
public void checkClientTrusted(final java.security.cert.X509Certificate[] arg0, final String arg1)
throws CertificateException {
// Do Nothing
}

@Override
public void checkServerTrusted(final java.security.cert.X509Certificate[] arg0, final String arg1)
throws CertificateException {
// Do Nothing
}

@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
};
}

No comments: