weblogic.net.http.HttpUnauthorizedException: Proxy or Server Authentication Required - proxy

I am trying to connect to a REST API in an application deployed on weblogic 10.3.6. The sample code works fine when run independently (outside weblogic server). But when I deploy the same code it starts giving me this error
Failed to communicate with proxy: proxy.xxx.xxx/xxxx. Will try connection api.forecast.io/443 now.
weblogic.net.http.HttpUnauthorizedException: Proxy or Server Authentication Required
at weblogic.net.http.HttpURLConnection.getAuthInfo(HttpURLConnection.java:297)
at weblogic.net.http.HttpsClient.makeConnectionUsingProxy(HttpsClient.java:440)
at weblogic.net.http.HttpsClient.openServer(HttpsClient.java:351)
at weblogic.net.http.HttpsClient.New(HttpsClient.java:527)
at weblogic.net.http.HttpsURLConnection.connect(HttpsURLConnection.java:239)
Code that we are running is as below
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) { // should never happen
e.printStackTrace();
}
try {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.xxxx.xxxx", xxxx));
URL url = new URL("https://api.forecast.io/forecast/xxxxxxxxx/12.9667,77.5667");
HttpURLConnection conn = (HttpURLConnection)url.openConnection(proxy);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
Our proxy is a company proxy and doesn't have any username/password. We are stuck on this issue for sometime now. Any suggestions/pointers will be really appreciated.

Related

Implement truststore manager on server to validate peer X509 certificates

I have a 2 way SSL implementation between multiple clients and servers running on spring-boot. On the server's truststore, I am adding the domain certs for client as we have clients with similar intermediate and root certs and only want to authenticate clients which have their domain certs present in our truststore or return an exception( I am aware that SSL implementation is for authentication and this should be taken care in authorization part but this is a requirement :( ). I want to customize the truststore implementation to check for presence of domain cert and not the whole chain if client sends only the domain cert while still making sure all other validations take place as-is via the default truststore implementation.
In order to do this I have implemented my custom TrustManager and offloaded the part of other validation to the default implementation of TrustStoreManager.
char [] password = new String("abcde").toCharArray();
String keyFilename = "some-path/server-truststore.jks";
static Map<String,String> map = new HashMap<>();
KeyStore trustStore= null;
try {
trustStore = KeyStore.getInstance("JKS");
} catch (KeyStoreException e) {
e.printStackTrace();
}
try {
trustStore.load(new FileInputStream(keyFilename), password);
} catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
}
try {
Enumeration<String> trustStoreEnum= trustStore.aliases();
while(trustStoreEnum.hasMoreElements()){
String nextElement= trustStoreEnum.nextElement();
X509Certificate certificate = (X509Certificate)trustStore.getCertificate(nextElement);
String key=certificate.getSubjectDN().getName().trim();
map.put(key,certificate.getSerialNumber().toString());
}
} catch (KeyStoreException e) {
e.printStackTrace();
}
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
try {
tmf.init(trustStore);
} catch (KeyStoreException e) {
e.printStackTrace();
}
X509TrustManager x509Tm = null;
for(TrustManager tm :tmf.getTrustManagers()){
logger.info(tm.toString());
x509Tm = (X509TrustManager) tm;
break;
}
//Truststrore Manager implementation
final X509TrustManager finalTm = x509Tm;
TrustManager[] x509ExtendedTrustManager = new TrustManager[] {
new X509TrustManager() {
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return finalTm.getAcceptedIssuers();
}
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) throws CertificateException {
logger.info("client blah");
finalTm.checkClientTrusted(certs,authType);
for(X509Certificate x509Certificate: certs){
String certName=x509Certificate.getSubjectDN().getName().trim();
if(!(map.containsKey(certName) && map.get(certName).equals(x509Certificate.getSerialNumber().toString())))
throw new CertificateException("Certificate not present in truststore");
}
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) throws CertificateException {
logger.info("server blah");
finalTm.checkServerTrusted(certs, authType);
}
}
};
The problem is that this implementation is never called even though I set it in my SSLContext on the server and instead the default truststore manager implementation is used.
try {
SSLContext sc = SSLContext.getInstance("TLS");
char [] password2 =
new String("changeit").toCharArray();
String keyFilename2 = "/<some-path>/server-keystore.jks";
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keyFilename2), password2);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("NewSunX509");
kmf.init(ks, "changeit".toCharArray());
KeyManager[] kms = kmf.getKeyManagers();
sc.init(kms, x509ExtendedTrustManager, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
SSLContext.setDefault(sc);
} catch (GeneralSecurityException e) {
logger.error(e.getMessage());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
logger.info("SSL context set");
}
I am not sure if it is because we cannot set a SSLContext on a port that has already been initialized. I would like to know if there is a better way to do this or can we initalize SSLContext on the same port?
Thanks in advance!

TCP socket client using Spring Boot Web

I'm developing a web application using Spring Boot Web and I want to communicate with a TCP socket server using IP and Port (connect, send, receive and disconnect).
I'm new to Spring Boot and I searched many days in the internet without any working result and the Websocket solution will not work in this case.
UPDATE (please confirm)
I think that I can use the standard java.io.* and java.net.* in Spring Boot Web juste like any other Java Program:
try {
try (Socket clientSocket = new Socket(IP, PORT);
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(), true);
BufferedReader br = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()))) {
System.out.println("Connected to server");
String str = "test";
out.write(str);
out.flush();
char[] cbuf = new char[size];
br.read(cbuf, 0, size);
System.out.println(cbuf);
}
} catch (IOException ex) {
ex.printStackTrace();
}
This is my own version of a simple tcp client developed for SpringBoot.
First, you have to open the connection with the openConnection() method. Then, you can send messages with sendMessage() method and receive messages with takeMessage() method.
#Service("socketClient")
public class SocketClient {
#Value("brain.connection.port")
int tcpPort;
#Value("brain.connection.ip")
String ipConnection;
private Socket clientSocket;
private DataOutputStream outToTCP;
private BufferedReader inFromTCP;
private PriorityBlockingQueue<String> incomingMessages = new PriorityBlockingQueue<>();
private PriorityBlockingQueue<String> outcomingMessages = new PriorityBlockingQueue<>();
private final Logger log = LoggerFactory.getLogger(this.getClass());
private Thread sendDataToTCP = new Thread(){
public void run(){
String sentence = "";
log.info("Starting Backend -> TCP communication thread");
while(true){
try {
sentence = incomingMessages.take();
outToTCP.writeBytes(sentence + '\n');
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
private Thread getDataFromTCP = new Thread(){
public void run(){
log.info("Starting TCP -> Backend communication thread");
while(true){
String response = "";
try {
response = inFromTCP.readLine();
if (response == null)
break;
outcomingMessages.put(response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
};
public void openConnection(){
try {
this.clientSocket = new Socket(ipConnection, tcpPort);
outToTCP = new DataOutputStream(clientSocket.getOutputStream());
inFromTCP = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
getDataFromTCP.start();
sendDataToTCP.start();
} catch (IOException e) {
e.printStackTrace();
}
}
//Send messages to Socket.
public void sendMessage(String message) throws InterruptedException {
incomingMessages.put(message);
}
//Take Message from Socket
public String takeMessage() throws InterruptedException {
return outcomingMessages.take();
}
}

Spring MVC - calling methods in #ResponseBody

I am Spring MVC beginner and I want to call rest in #ResponseBody. My external node server doesn't react on that method. I don't got message about request in my server console. Without UserRest it works. I would be grateful for your help
#Controller
public class AjaxController {
#RequestMapping(value= "user", method=RequestMethod.GET)
public #ResponseBody String login (){
UserRest ur = new UserRest();
Response r = ur.getUserName(2);
Gson gs = new Gson();
String str = gs.toJson(r);
return str;
}
}
Response getUserName(int userID){
Response response = new Response();
StringBuilder total = new StringBuilder();
try {
URL url = new URL(Properties.SERVER_SECURE_URL + "users/" + userID);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setDoOutput(false);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization","1Strajk");
response.setMessageCode(urlConnection.getResponseCode());
if(response.getMessageCode()==Response.MESSAGE_OK) {
InputStream in = urlConnection.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(!total.toString().isEmpty()){
response.setObject(total.toString());
}
urlConnection.disconnect();
}
return response;
}
I resolve it. I forgot about SSL connection. Before calling rest I called that method:
public class SSLUtils {
public static void trustEveryone() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
context.getSocketFactory());
} catch (Exception e) { // should never happen
e.printStackTrace();
}
}
}

Jersey with self signed certificate

I am currently working in a dev environment where we are using self signed certificates. I've been trying for a little over a day now to get jersey to ignore the self signed certificate. This is purely for a POC environment, I wouldn't dream of doing thi sin production. While I've found many answers on the interweb about how to make this work, something is still off.
Here's my current test class:
public class JerseyTestClient {
private static final Logger LOG = Logger.getLogger(JerseyTestClient.class.getName());
public static void sendTestRequest() {
try {
Client client = Client.create(configureClient());
WebResource webResource = client.resource("https://server/endpoint/");
ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
List<Hardware> output = response.getEntity(new GenericType<List<Hardware>>() {});
LOG.severe("Output from Server .... \n");
LOG.severe("Nr of entries: " + output.size());
} catch (Exception e) {
LOG.log(Level.SEVERE, " test request failed", e);
}
}
public static ClientConfig configureClient() {
TrustManager[ ] certs = new TrustManager[ ] {
new X509TrustManager() {
#Override
public X509Certificate[] getAcceptedIssuers() {
LOG.severe("getAcceptedIssuers");
return null;
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
LOG.severe("checkServerTrusted");
}
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
LOG.severe("checkClientTrusted");
}
}
};
SSLContext ctx = null;
try {
ctx = SSLContext.getInstance("TLS");
ctx.init(null, certs, null);
} catch (java.security.GeneralSecurityException e) {
LOG.log(Level.SEVERE, "Error", e);
}
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
LOG.severe("verify");
return true;
}
});
ClientConfig config = new DefaultClientConfig();
try {
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
LOG.severe("verify");
return true;
}
},
ctx
));
} catch(Exception e) {
LOG.log(Level.SEVERE, "Error", e);
}
return config;
}
}
While everything seems right, the log lines in the TrustManager and in the HostnameVerifier never show up in the logs, and the connection still failes with an SSL Handshaking Exception on the get(ClientResponse.class).
I've been going over this for a while now and when I compare this to all the tutorials and people saying they fixed it, I can't find a difference.
If someone could point out the flaw that should be in there somehwere....
My company BITPlan has published an open source project to simplify handling of Jersey 1.19 see
https://github.com/BITPlan/com.bitplan.simplerest
The test case:
https://github.com/BITPlan/com.bitplan.simplerest/blob/master/src/test/java/com/bitplan/rest/test/TestBasicAuth.java
creates an SSL connection with no client certificate being used.
This leads to:
Schwerwiegend: SSL Client certificate is missing for /hello/hello
but the testcase nevertheless runs
The handling on the Clientside is done with:
https://github.com/BITPlan/com.bitplan.simplerest/blob/master/src/main/java/com/bitplan/rest/SSLClientHelper.java
if you should have any trouble with this you might want to file an issue
via https://github.com/BITPlan/com.bitplan.simplerest/issues

Receive MapMessage by Consumer shows nothing

Hello i am facing a strange(for me ) problemm with MapMessage in ActiveMQ. My code produces no error but it shows nothing.
Producer code:
public void sendMapMessageTopic(String topicName) throws Exception {
try {
initConnectionTopic(topicName);
mapMessage = session.createMapMessage();
mapMessage.setIntProperty("Age", 24);
mapMessage.setStringProperty("Full Name", "Konstantinos Drakonakis");
mapMessage.setStringProperty("Height", "178cm");
List<String> data = new ArrayList<String>();
data.add("Company");
data.add("Project");
mapMessage.setObject("data", data);
Map<String, Object> specs = new HashMap<String, Object>();
specs.put("data", data);
mapMessage.setObject("specs", specs);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
producer.send(mapMessage);
} catch (Exception e) {
System.out.println("Exception while sending map message to the queue" + e.getMessage());
throw e;
} finally {
if (connection != null) {
connection.close();
if (session != null) {
session.close();
}
}
}
}
Consumer code:
public void startReceivingMapMessageTopic(String topicName) throws Exception {
try {
//get connection factory
connectionFactory = new ActiveMQConnectionFactory(username, password, brokerUrl);
//create a connection
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
//create destination(unless it already exists)
queue = session.createTopic(topicName);
consumer = session.createConsumer(queue);
messageMap = (MapMessage) consumer.receive(1000);
if (messageMap instanceof MapMessage) {
MapMessage m = messageMap;
System.out.println("The contents of MapMessage is: " + m.getStringProperty("Age"));
}
System.in.read();
consumer.close();
connection.close();
session.close();
} catch (Exception e) {
System.out.println("Exception while sending message to the queue" + e.getMessage());
throw e;
}
}
Main method for Producer:
public static void main(String[] args) {
//connect to the default broker url
ActiveMQQueueSender sender = new ActiveMQQueueSender("tcp://localhost:61616", "admin", "admin");
try {
sender.sendMapMessageTopic("Map Message Topic");
} catch (Exception ex) {
System.out.println("Exception during" + ex.getMessage());
}
}
Main method for consumer:
public static void main(String[] args) {
ActiveMQQueueReceiver receiver = new ActiveMQQueueReceiver("tcp://localhost:61616", "admin", "admin");
try {
receiver.startReceivingMapMessageTopic("Map Message Topic");
} catch (Exception ex) {
System.out.println("Exception during receival in main class" + ex.getMessage());
}
}
But still i get nothing. Any ideas?

Resources