Jetty httpclient add proxy socks4 - proxy

When i'm trying to send request via jetty httpClient with new Socks4Proxy(socksHost, socksPort); received: java.util.concurrent.ExecutionException: java.io.IOException: SOCKS4 tunnel failed with code 91
HttpClient httpClient = new HttpClient();
ProxyConfiguration proxyConfig = httpClient.getProxyConfiguration();
Socks4Proxy proxy = new Socks4Proxy(socksHost, socksPort);
proxyConfig.getProxies().add(proxy);
httpClient.start();
String url = config.getProperty(stringUrl);
Request request = httpClient.newRequest(url);
request.method(HttpMethod.GET);
request.onResponseContent(new BufferingResponseListener() {
#Override
public void onComplete(Result result) {
String s = getContentAsString();
logger.debug("Received http response message: '{}', status: '{}'", s, result.getResponse().getReason());
}
});
try {
request.send();
} catch (Exception e) {
throw new RuntimeException(e);
}

Per https://www.openssh.com/txt/socks4.protocol
Your 91 status means that request was rejected or failed. The user or source program is not authorized to access the proxy server.
Perhaps your SOCKS4 proxy has an authentication requirement.

Related

Spring RestTemplate Connection Timeout

Any help or hint would be greatly appreciated it.
I tried the below RestTemplate code in Eclipse and Intellij and I get the same connection timeout error. If I run it on a browser I am able to connect.
enter image description here
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "https://registry-relationship-dev.api.non-prod-uw2.hponecloud.io/ocrel-registry/v2/node/sub.node.0025s": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect
try {
String tempUrl = registryUrl;
if (roleInput.getNodeId() != null) {
tempUrl = tempUrl + roleInput.getNodeId();
}
URI uri = new URI(tempUrl);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization",auth);
headers.set("Content-Type","application/json");
HttpEntity<String> entity = new HttpEntity<String>("parameters",headers);
RestTemplate restTemplate = new RestTemplate();
// ResponseEntity<String> response = restTemplate.exchange(tempUrl,HttpMethod.GET, entity,String.class);
ResponseEntity<NodeModel> response1 = restTemplate.exchange(tempUrl,HttpMethod.GET, entity,NodeModel.class);
NodeModel response = restTemplate.getForObject("https://registry-relationship-dev.api.non-prod-uw2.hponecloud.io/ocrel-registry/v2/node/sub.node.0025s",NodeModel.class);
System.out.println("response from registry:"+response);
}
log.info("createRole,After call authLibService.validateToken(auth):"+auth);
} catch (Exception e) {
log.error("Failed to check permission, createRole getMessage error: {}", e.getMessage());
log.error("Failed to check permission, createRole getStackTrace error: {}", e.getStackTrace());
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}

HTTP POST is not working with Webclient but working with RestTemplate

I am getting Error while making POST calls with webclient as below
org.springframework.web.reactive.function.client.WebClientRequestException: An existing connection was forcibly closed by the remote host; nested exception is java.io.IOException: An existing connection was forcibly closed by the remote host
But same request working fine with restetemplate, both code as below
RestTemplate restTemplate = new RestTemplate();
final String baseUrl = "https://somehost/rest/v1/leads.json";
URI uri = null;
try {
uri = new URI(baseUrl);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer 39131a98-7a53-497f-8e04-ca08c35a7775:sj");
HttpEntity<Lead> request = new HttpEntity<>(convertToLead(consent), headers);
ResponseEntity<LeadResponse> result = restTemplate.postForEntity(uri, request, LeadResponse.class);
System.out.println(result.getBody().toString());
Failed with Webclient code
ResponseEntity<Response> leadResponse = marketoWebClient.post().uri("/leads.json").bodyValue(lead).exchange()
.flatMap(clientResponse -> clientResponse.toEntity(LeadResponse.class).doOnSuccess(response -> {
if (clientResponse.statusCode().isError()) {
logger.debug("Error Details = {} {}", clientResponse.statusCode(), response);
}
})).block();

Spring RestTemplate + Basic Authentication + Post with request Body: 500 Internal Server Error

I am looking for a working approach for Rest Client using Spring (5.x) RestTemplate with Basic Authentication + passing Request Body as HTTP Post.
NOTE: the service works fine If I hit request using postman/ other rest client, instead of a java client/ test class.
I am getting 500 Internal Server Error
org.springframework.web.client.HttpClientErrorException: 500 Internal Server Error
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:704)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:459)
at com.xxx.xxx.xxx.utils.Util.updateFlag(Util.java:125)
at com.xxx.xxx.xxx.utils.UtilsImplTest.testUpdateFlag(UtilsImplTest.java:122)
My Test class:
#Test
public void testUpdateFlag() {
Request request = new Request();
request.setUserId("aa");
request.setFlag("Y");
request.setValue("D");
Response response = null;
try {
response = util.updateFlag(request);
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
assertNotNull(response);
}
My Implementation util class: where I am setting Basic Authorization in header.
#Autowired private RestTemplate restTemplate;
private HttpHeaders getHeaders(){
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + <base64_encrypted_password>);//500
// headers.setContentType(MediaType.APPLICATION_JSON); //401
return headers;
}
public Response updateFlag(Request request) throws JsonProcessingException, URISyntaxException {
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<Request> requestEntity = new HttpEntity<>(request, getHeaders());
Response response = restTemplate.postForObject(url, requestEntity, Response.class);
return response;
}
If I comment out the basic authorization line in getHeaders() method, then it throws 401 Unauthorized, which is fairly logical.
org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:94)
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:79)
at org.springframework.web.client.ResponseErrorHandler.handleError(ResponseErrorHandler.java:63)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:777)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:730)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:704)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:459)
at com.xxx.xxx.xxx.utils.Util.updateFlag(Util.java:125)
at com.xxx.xxx.xxx.utils.UtilsImplTest.testUpdateFlag(UtilsImplTest.java:122)
I have tried almost every option suggested over stackoverflow in similar content, unable to identify the exact root cause why setting authorization in header doesn't validate & throws 500 Internal Server Error.
I have spent quite a handful time investigating, with no luck. Appreciate any pointers.

Redirect to another URL and back for Certifcate base Login

Currently i developing an application which have two routes which are in different domain.
Example :
Route 1: https://test.apps.com
Route 2: https://test.cert-apps.com
Users uses Route 1 to access the application. In the Login page there is an option for Certificate based login . But certificate based authentication is only enabled in route 2.
So how do i do the certificate based authentication by redirecting from Route 1 to Route 2 and once client is authenticated redirect to route 1.
Following are the code that i currently using which are not working:
#Controller
#RequestMapping("/login")
public class LoginContr {
#RequestMapping("/certificate")
public String message(HttpServletRequest request, HttpServletResponse response) {
try {
sendGET();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "login";
}
#RequestMapping("/extractcertificate")
private String extractEmailFromCertificate(HttpServletRequest request) {
String email = "";
//Code to extract email from certificate
return email;
}
private static void sendGET() throws IOException {
URL obj = new URL("https://test.cert-apps.com/login/extractcertificate");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
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());
} else {
System.out.println("GET request not worked");
}
}
}
The above code gives the error:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
sendGet() method sends a request to Route 2 and calls /extractcertificate webservice to do certificate based authentication and once its done it will retrive the email address.
Technology using for app: Java,Spring,Angualar 4, Cloud Foundary
Is there any alternative to do this or any inbuilt implementation , any tips would be great advantage..

Sending headers/body after the websocket session is established

I am using org.eclipse.jetty.websocket.client.WebSocketClient to establish a websocket connection.
After the initial handshake(Protocol switch/Upgrade) the websocket session is established.
Here is the code snipped i am using:
WebSocketClient client = new WebSocketClient();
client.start();
URI echoUri = new URI("destinationURI");
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("myCustomHeader", "CustomHeader");
client.connect(socket, echoUri, request);
Collection<WebSocketSession> sessions = client.getConnectionManager().getSessions();
for (WebSocketSession webSocketSession : sessions) {
webSocketSession.getRemote().sendString("<Custome message>");//I am able to recieve the messages //to the configured message handler
}
My message handler looks like:
#Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message//This is what i sent above) throws Exception {
session.getHandshakeHeaders();//This has "myCustomHeader", "CustomHeader"
BinaryMessage binaryMessage = new BinaryMessage(new String(
"Hello . This is message sent from server").getBytes());
session.sendMessage(binaryMessage);
}
Is it possible to send a custom header, after the web socket session is established?
Here is what i tried:
WebSocketClient client = new WebSocketClient();
client.start();
URI echoUri = new URI("destinationURI");
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setHeader("myCustomHeader", "CustomHeader");
client.connect(socket, echoUri, request);
Collection<WebSocketSession> sessions = client.getConnectionManager().getSessions();
for (WebSocketSession webSocketSession : sessions) {
webSocketSession.getUpgradeRequest().setHeader("mySecondCustomHeader","MySecondCustomHeader");
webSocketSession.getRemote().sendString("<Custome message>");//I am able to recieve the messages //to the configured message handler
}
I am only getting myCustomHeader and not mySecondCustomHeader in session.getHandshakeHeaders()
#Override
protected void handleTextMessage(WebSocketSession session,
TextMessage message//This is what i sent above) throws Exception {
session.getHandshakeHeaders();//This has "myCustomHeader", "CustomHeader"
BinaryMessage binaryMessage = new BinaryMessage(new String(
"Hello . This is message sent from server").getBytes());
session.sendMessage(binaryMessage);
}
s it possible to send a custom header, after the web socket session is
established?
No, it is not possible. Once the HTTP negotiation has concluded, the connection only uses binary frames to communicate and cannot do more HTTP interactions.

Resources