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.
Related
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.
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 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 a curl request which looks like below:-
curl -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '{"Request": {"Orders":[{"id_sales_order": 160407400833822,"address_billing": {"first_name":"John","last_name": "Doe","phone": "1234567","phone2": "1234","address1": "Sesamestreet 123","city": "Berlin","postcode": "12345","country": "Germany"}}]}}' "https://debraj:debrajmanna#example.com/oms-api/?Action=UpdateOrderInformation&ServiceName=OMS&Signature=e436d6c7c930fa37a30a8b67051cb4531dad92b0c904a5a009bb4529a762dcd7&Timestamp=2016-04-09T19%3A14%3A12%2B0530&Version=1.0"
This is giving output:-
{"ErrorResponse":{"Head":{"RequestAction":"UpdateOrderInformation","ErrorType":"Sender","ErrorCode":0,"ErrorMessage":"Some elements were not processed"},"Body":{"UpdateOrderInformation":[{"ErrorCode":null,"ErrorMessage":"Order with source id: 160407400833822 was not found","Position":0}]}}}
To implement this in Java I have the below java code. But the java code is not behaving as expected. Can some let me know what I am doing wrong?
public class CurlMain {
public static void main(String[] args) throws Exception {
String url = "https://example.com/oms-api/";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
String authStr = String.format("%s:%s", "debraj", "debrajmanna");
String body = "{'Request': {'Orders':[{'id_sales_order': 160407400833822,'address_billing': {'first_name':'John','last_name': 'Doe','phone': '1234567','phone2': '1234','address1': 'Sesamestreet 123','city': 'Berlin','postcode': '12345','country': 'Germany'}}]}}";
String encodedAuthStr = Base64.getEncoder().encodeToString(authStr.getBytes(StandardCharsets.UTF_8));
con.setRequestProperty("Authorization", "Basic " + encodedAuthStr);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
String urlParameters = "Action=UpdateOrderInformation&ServiceName=OMS&Signature=e436d6c7c930fa37a30a8b67051cb4531dad92b0c904a5a009bb4529a762dcd7&Timestamp=2016-04-09T19%3A14%3A12%2B0530&Version=1.0";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.writeBytes(body);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
HttpsURLConnection.setFollowRedirects(true);
Map<String, List<String>> headers = con.getHeaderFields();
System.out.println(headers.toString());
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Curl Response " + response.toString());
}
whereas the java code is printing:-
{"ErrorResponse":{"Head":{"RequestAction":"","ErrorType":"Sender","ErrorCode":"9","ErrorMessage":"E009: Access Denied"},"Body":""}}
I don't have access to the server code or server configuration. My goal is to send the same curl request through the java code and get the same response.
I am using java 8.
Am I missing anything?
Appending the query parameters to the url solved the issue like below:-
URL obj = new URL(new StringBuilder(url).append("?").append(urlParameters).toString());
...
//wr.writeBytes(urlParameters);
I am trying to write a Java code where I need to fetch data from a RESTful Api using Apache HttpClient.
My web server has a self signed certificate. The code I have used is as follows:
public class WebClientDevWrapper {
public static HttpClient wrapClient(HttpClient base) {
try {
ClientConnectionManager ccm = base.getConnectionManager();
SSLSocketFactory sslsf = new SSLSocketFactory(new TrustSelfSignedStrategy());
Scheme https = new Scheme("https", 444, sslsf);
ccm.getSchemeRegistry().register(https);
return new DefaultHttpClient(ccm, base.getParams());
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
public static void main(String[] args) throws ClientProtocolException, IOException{
HttpClient client ;
client = new DefaultHttpClient();
client = WebClientDevWrapper.wrapClient(client);
HttpGet request = new HttpGet("https://localhost/restapi");
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}
}
On running this code, I am getting the following error:
"javax.net.ssl.SSLException: Certificate for doesn't contain CN or DNS subjectAlt"
Please help.
You need to import the SSL certificate in your JAVA. Use the below line
<JAVA_HOME>\bin\keytool -import -v -trustcacerts
-alias [Your Alias name] -file [Your Certificate location]
-keystore [Keystore location] -keypass [Your Password]
-storepass [Your Password]