I'm trying to hit api1 which gives me a token for authentication for api2. However i'm getting this error from Connection.getOutputStream() Method threw 'javax.net.ssl.SSLException' exception.
Any idea how to fix this?
public HttpsURLConnection getHttpsURLConnection(HttpParameterSetter parameters, URL url, String method) throws IOException {
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod(method);
parameters.getHeaders().forEach(connection::setRequestProperty);
return connection;
}
public String requests(URL url) throws Exception {
url = new URL(url.toString() + "?" + parameters.toString());
HttpsURLConnection connection = getHttpsURLConnection(this.parameters, url, this.method);
connection.setDoOutput(true);
BufferedReader in = null;
DataOutputStream wr = null;
try {
if (!payload.equals("")) {
wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(this.getPayload());
wr.flush();
wr.close();
}
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
StringBuilder inputLine = new StringBuilder();
String line;
while ((line = in.readLine()) != null)
inputLine.append(line);
return inputLine.toString();
} catch (Exception e) {
log.error("Exception occurred during token call "+e.getMessage());
throw e;
} finally {
try{
if (wr != null)
wr.close();
}catch (Exception e){
log.error("Error occurred while closing DataOutputStream in the token call: "+e.getMessage());
}
try{
if (in != null)
in.close();
}catch (Exception e){
log.error("Error occurred while closing BufferedReader in the token call: "+e.getMessage());
}
}
}**strong text**
Does the server you are trying to connect to use a self-signed certificate?
If so, please make sure you have imported the self-signed certificate into your jre KeyStore.
Here is an example:
keytool -keystore "%JAVA_HOME%\jre\lib\security\cacerts" -importcert -alias <alias> -file <certificate> -trustcacerts -keypass changeit -storepass changeit
<certificate> is the filename of the certificate, such as xxx.cer or xxx.crt.
Related
try to call rest postman service with the code below
it works fine in Java 8 but java 6 returns this error.
error returns in java 6
public class Test {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String userName = "postman";
String password = "password";
try {
String encodedCredintals =
"Basic " + Base64.encode((userName + ":" + password).getBytes());
URL url = new URL("https://postman-echo.com/basic-auth");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
// conn.setRequestProperty("Authorization", "Basic cG9zdG1hbjpwYXNzd29yZA==");
conn.setRequestProperty("Authorization", encodedCredintals);
conn.setRequestProperty("Content-Type", "application/json");
System.out.println(conn.getResponseCode() + " " + conn.getResponseMessage());
InputStream inputStream = null;
try {
inputStream = conn.getInputStream();
System.out.println(inputStream);
} catch (IOException e) {
System.out.println(e.getMessage());
}
InputStreamReader isReader = new InputStreamReader(inputStream);
//Creating a BufferedReader object
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while ((str = reader.readLine()) != null) {
sb.append(str);
}
System.out.println(sb.toString());
conn.disconnect();
JSONParser parser = new JSONParser();
JSONObject jsonOject = (JSONObject) parser.parse(sb.toString());
String value = jsonOject.get("authenticated").toString();
System.out.println(value + "");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I added certificates to java 6 home through these command
keytool -import -noprompt -trustcacerts -alias postman -file C:\ME\PostmanCer.cer -keystore "C:/Program Files/Java/jdk1.6.0_45/jre/lib/security/cacerts" -storepass changeit
and check the whole list to ensure that is added successfully
keytool -list -v -keystore "C:/Program Files/Java/jdk1.6.0_45/jre/lib/security/cacerts"
and it's added.
how can I solve this issue?
I'm new to certificate concept can any one help how to send the certificate in https request.
My CURL command is below:
curl -d "grant_type=password&client_id=SmartRest&client_secret=594a27f3-4432-4d37-9196-2ba49de52758&username=user123&password=welcome123" https://xxxxxxx.xxx.in:8543/auth/realms/restapi/protocol/openid-connect/token --cacert ./ca_bundle.crt
Same thing i need to send in my java code, i have only one .crt file, I don't have keypass or anything.
I trusted the certificate by below keytool command.
keytool -import -trustcacerts -file "ca_bundle.crt" -alias "alias" -keystore "C:\Program Files\Java\jdk1.8.0_131\jre\lib\security\cacerts"
Below code works fine, no need to skip ssl validation.
public static void main(String[] args) throws Exception {
HttpsURLConnection con = (HttpsURLConnection) new URL("https://xxxx.xxx.xx:8543/auth/realms/restapi/protocol/openid-connect/token").openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String urlParameters = "grant_type=password&client_id=SmartRest&client_secret=594a27f3-4432-4d37-9196-2ba49de52758&username=user123&password=welcome123";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
i got the result.
I'm in a Spring boot service, that will be within a microservice, attempting to connect to an external SOAP Web Service, that requires a cert that was created by that service and a password. This is being written in Windows, but will need to be run on Unix. Right now, I've hardcoded some things for Windows. This is what I have coded for my side, but I'm getting an error on httpConn.getInputStream():
"sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target".
Can someone help me understand what I'm missing?
public String getSoapData(String contentType) throws IOException, NoSuchAlgorithmException, KeyManagementException, CertificateException, KeyStoreException {
StringBuilder retVal = new StringBuilder();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
// get user password and file input stream
char[] password = "MYPass".toCharArray();
java.io.FileInputStream fis = null;
//X509Certificate caCert = null;
//CertificateFactory cf = CertificateFactory.getInstance("X.509");
try {
fis = new java.io.FileInputStream("C:\\MyCerts\\dev_HubExplorer1.pfx");
ks.load(fis, password);
//caCert = (X509Certificate)cf.generateCertificate(fis);
//ks.setCertificateEntry("caCert", caCert);
} catch (Exception e) {
Common.screenPrint("Exception while importing certificate:%s%s", Common.CRLF, e.getMessage());
} finally {
if (fis != null) {
fis.close();
}
}
tmf.init(ks);
//TODO (GWL) Need to get this from a configuration file/db.
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
URL url = new URL(_publicRecordURL);
HttpsURLConnection httpConn = (HttpsURLConnection) url.openConnection();
httpConn.setSSLSocketFactory(sslContext.getSocketFactory());
byte[] bytes = _requestTemplate.getBytes();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length", String.valueOf( bytes.length ) );
httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction",_soapAction);
httpConn.setRequestProperty("Accept","text/xml");
httpConn.setRequestMethod( "POST" );
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
//Everything's set up; send the XML that was read in to b.
OutputStreamWriter writer = new OutputStreamWriter(httpConn.getOutputStream());
writer.write(_requestTemplate);
writer.flush();
//Read the response and write it to standard out.
InputStreamReader isr = new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null) {
retVal.append(inputLine + Common.CRLF);
System.out.println(inputLine);
}
in.close();
return retVal.toString();
}
you can follow this stackoverflow answer to get the solution of this problem :
https://stackoverflow.com/a/12146838/7801800
I have HTTPS page calls working fine and I have HTTP Basic Auth working fine what I can not do is get Basic Auth running on a HTTPS connection.
I attach a code example but it doesn't work. I keep getting a 403. I have checked the username and password and it has been successful when testing it with the RESTClinet addon from Firefox.
Any help would be great. Thanks.
private static void getAPITest() throws MalformedURLException, IOException
{
try {
System.setProperty("javax.net.ssl.trustStore","/home/USER/CERTS/myTrustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "PASSWORD");
Authenticator myAuth = new Authenticator()
{
#Override
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("USERNAME", "PASSWORD".toCharArray());
}
};
Authenticator.setDefault(myAuth);
String httpsURL = "https://someurlandapi.com";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
//con.setRequestProperty("Authorization", "Basic " + authString);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
}
ins.close();
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
it turns out don't have a space before the basic:
con.setRequestProperty("Authorization", "Basic " + authStringEnc);
and it needed:
conn.setRequestProperty("User-Agent", "Mozilla/5");
A quick note for anyone doing this if you are creating your own truststore you will need to add the sites/urls SSL certificate chain. In firefox you can click on the padlock > More information > security > view certificates. From there you can highlight the certificate export with chain it then add it to your truststore with the keytool:
keytool -import -file websitecertificate.pem -alias websitecert -keystore myTrustStore
I don't think PasswordAuthentication is doing what you want. But basic auth is really easy to handle yourself. If you're in Java8 it is simply Base64.getEncoder().encodeToString( ("USERNAME" + ":" + "PASSWORD").getBytes()).
I have .p12 certificate file which needs to be included in every sent to server from my java code.
When i run sample code from linux its gives me exception
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: timestamp check failed
My java code is below :
HttpsURLConnection con = null;
try
{
System.out.println("Calling webservice ..... ");
char[] passw = "mypassword".toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS12");
InputStream keyInput = new FileInputStream( "/usr/local/KEYSTORE.p12");
ks.load(keyInput, passw );
keyInput.close();
System.out.println("Reading certificate file Completed");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, passw);
System.out.println("Set SSL certificate");
SSLContext sclx = SSLContext.getInstance("SSL");
sclx.init( kmf.getKeyManagers(), null, new SecureRandom());
SSLContext.setDefault(sclx);
HttpsURLConnection.setDefaultSSLSocketFactory(sclx.getSocketFactory());
URL url = new URL("https://myurl.server.com");
con = (HttpsURLConnection)url.openConnection();
System.out.println("Connection successfull");
//con.setSSLSocketFactory(sclx.getSocketFactory());
System.out.println("Token Id 026F800E-562D-4B0F-BC56-AC16895072F4");
if(con!=null)
{
System.out.println("Inside connection");
con.setRequestProperty("Content-Type","application/json;charset=utf-8");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setRequestProperty("Token-Id","026F800E-562D-4B0F-BC56-AC16895072F4");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setDefaultUseCaches(false);
con.setRequestMethod("POST");
con.connect();
OutputStreamWriter os = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
os.write("request String");
os.flush();
os.close();
InputStreamReader dis = new InputStreamReader(con.getInputStream(),"UTF-8");
if (null != dis)
{
System.out.println("Reading response from webservice 1");
BufferedReader reader = new BufferedReader(dis);
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
catch(IOException ioex)
{
System.err.println("Exception : "+ioex);
e.printStackTrace();
}
catch(Exception ex){
ex.printStackTrace();
}
finally{
if(con != null) {
con.disconnect();
}
}
Its work on windows server but gives exception on linux server.
Please any one help me to resolved this.