SSLPeerUnverifiedException:"peer not authenticated" while using groovy's RestClient with ignoreSSLIssues() - java

I am writing an integration test for my Rest end point and I have choosen groovy's RestClient. My rest call is on "HTTPS" and I started facing SSL exceptions.
While digging more into this, I was happy to know about ignoreSSLIssues() method (http://groovy.codehaus.org/modules/http-builder/doc/ssl.html). As this is available in 0.7.1 version of HttpBuilder, I upgraded this jar and some dependent jars as well. So with this in place, as per the doc, i was hoping the below code to work -
def httpBuilder = new HTTPBuilder('baseurl')
httpBuilder.ignoreSSLIssues()
def resp = httpBuilder.get(path : 'restPath')
println resp
But this is still throwing javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated.
Any help on this is appreciated.
Thanks.

Just ran into this issue. You also get this deceptive error if you use an outbound proxy and haven't configured the HTTPBuilder class to use it explicitly.
You need to set the setProxy() method of HTTPBuilder. JVM OPTS such as -Dhttp.proxyHost do not seem to be respected by HTTPBuilder for whatever reason. My version looks something like this:
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.HEAD
def http = new HTTPBuilder( 'https://www.dev.java.net/' )
http.setProxy("my.proxy.com", 8080, "http")
http.ignoreSSLIssues()
def status = http.request( HEAD ) {
response.success = { it.status }
}

Related

What is the equivalent of .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE) in Netty world?

A small question regarding Netty and io.netty.handler.ssl.SslContext
In Tomcat and org.apache.http.ssl.SSLContexts, we have the possibility to perform the following:
HttpClient httpClient = HttpClients.custom()
.setSSLContext(SSLContexts.custom()
.loadKeyMaterial(someKeystorePropertlyInitialized)
.loadTrustMaterial(someTruststorePropertlyInitialized)
.build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
(Appreciate if we can leave the fonts and not wrap inside a code block)
This can for instance fix issues such as Caused by: java.security.cert.CertificateException: No subject alternative DNS name matching xxx found
(This question is not about if NoopHostnameVerifier.INSTANCE is the proper way to fix this.)
My question is, what is the equivalent in Netty of .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE), without .trustManager(InsecureTrustManagerFactory.INSTANCE), because I have a real trust store, I just want to skip the host name, not everything
Maybe something with reactor.netty.http.client.HttpClient; HttpClient.create() ?
Actually, Netty has hostname verification turned off by default -- see this issue. It looks like the library you're using (reactor-netty) might have it turned on. There appears to be a similar issue on reactor-netty's github which points to the solution, but the code snippet provided seems to do more than what's necessary. Essentially, all you need is to access the SSLEngine from the SslHandler and make sure the endpoint identification algorithm is empty/null:
HttpClient.create().secure(
ssl -> ssl.sslContext(sslContext)
.handlerConfigurator(handler-> {
SSLEngine engine = handler.engine();
SSLParameters params = new SSLParameters();
// ... set other SSL params
params.setEndpointIdentificationAlgorithm(null);
})
);

Unable to use mock HTTP/HTTPS get post request for json/xml response

Here is my code for junit.
I'm following this documentation for mock-server http://www.mock-server.com/
mockServerClient=new MockServerClient("127.0.0.1", 8080)
.when(
request()
.withMethod("POST")
.withPath("/login")
.withQueryStringParameters(
new Parameter("returnUrl", "/account")
)
.withCookies(
new Cookie("sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW")
)
.withBody(exact("{username: 'foo', password: 'bar'}")),
exactly(1)
)
.respond(
response()
.withStatusCode(401)
.withHeaders(
new Header("Content-Type", "application/json; charset=utf-8"),
new Header("Cache-Control", "public, max-age=86400")
)
.withBody("{ message: 'incorrect username and password combination' }")
.withDelay(new Delay(TimeUnit.SECONDS, 1))
);
The problem is request, response, exactly, exact, Header are not getting resolved in editor.
Some additional imports must be required but I couldn't find any working example/alternate to it.
All I need is simply mocking a server url request and responses to be used in Junits.
As an alternative to mock server I also tried Mockwebserver-https://github.com/square/okhttp/tree/master/mockwebserver
but it too has many limitations like I'm unable to do post using mockwebserver.
Also checking other options suggested here https://stackoverflow.com/questions/393099/mocking-http-server.
If anyone knows a working solution please help me.
Thanks in advance
Are you using Windows? If so maybe you can try my mock server instead?
https://mockserver.codeplex.com/

WS.url fails when proxy options are set in Play Framework 2.2.x

I am using WS to make a REST call to a server behind a proxy that required.
I tried to set proxyserver and port in application.conf and as JVM arg when I launch the application. But I keep getting "Error Code: 407 Proxy Authentication Required".
I tried to set ws.useProxyProperties at false and true, but it still doesn't work. I saw that it is a common problem, but no workaround has been published.
Do you have any idea?
Thanks
I managed to resolve this issue by using the dependancy
"com.ning" % "async-http-client" % "1.8.14"
And changing my code to
AsyncHttpClientConfig cf = new AsyncHttpClientConfig.Builder().setProxyServer(new
ProxyServer(host, port, user, pwd)).build();
c = new AsyncHttpClient(cf);
AsyncHttpClient.BoundRequestBuilder req = c.prepareGet("http://api.example.com/");
// and many other parameters ...

Jersey client not following redirects?

I am struggling to get a Jersey client that follows redirects, even though "I know I had this working earlier." (Haven't looked at the code in a while).
I thought had a complex case where it was failing when the redirect was from HTTP to HTTPS. But I cannot get even this simple test below to run:
package com.soliantconsulting.jira.test;
import static org.junit.Assert.*;
import com.sun.jersey.api.client.*;
import org.junit.Test;
public class JerseyClientTest {
public void test() {
Client c = Client.create();
c.setFollowRedirects( true );
WebResource r = c.resource("http://www.yahoo.com");
String response = r.get(String.class);
System.out.println( response );
}
}
When run, this code throws:
com.sun.jersey.api.client.UniformInterfaceException: GET http://www.yahoo.com returned a response status of 301 Moved Permanently
I've tried a couple different flavors of setting the redirect-follow option, so I must be doing something fundamentally wrong, I think.
Mac OS 10.9.4, JDK 1.7.0_65, Jersey 1.18.1, Eclipse Luna, Maven 3.2.3.

SOAP web service calls from Javascript

I'm struggling to successfully make a web service call to a SOAP web service from a web page. The web service is a Java web service that uses JAX-WS.
Here is the web method that I'm trying to call:
#WebMethod
public String sayHi(#WebParam(name="name") String name)
{
System.out.println("Hello "+name+"!");
return "Hello "+name+"!";
}
I've tried doing the web service call using the JQuery library jqSOAPClient (http://plugins.jquery.com/project/jqSOAPClient).
Here is the code that I've used:
var processResponse = function(respObj)
{
alert("Response received: "+respObj);
};
SOAPClient.Proxy = url;
var body = new SOAPObject("sayHi");
body.ns = ns;
body.appendChild(new SOAPObject("name").val("Bernhard"));
var sr = new SOAPRequest(ns+"sayHi",body);
SOAPClient.SendRequest(sr,processResponse);
No response seems to be coming back. When in jqSOAPClient.js I log the xData.responseXML data member I get 'undefined'. In the web service I see the warning
24 Mar 2011 10:49:51 AM com.sun.xml.ws.transport.http.server.WSHttpHandler handleExchange
WARNING: Cannot handle HTTP method: OPTIONS
I've also tried using a javascript library, soapclient.js (http://www.codeproject.com/kb/Ajax/JavaScriptSOAPClient.aspx). The client side code that I use here is
var processResponse = function(respObj)
{
alert("Response received: "+respObj);
};
var paramaters = new SOAPClientParameters();
paramaters.add("name","Bernhard");
SOAPClient.invoke(url,"sayHi",paramaters,true,processResponse);
I've bypassed the part in soapclient.js that fetches the WSDL, since it doesn't work
(I get an: IOException: An established connection was aborted by the software in your host machine on the web service side). The WSDL is only retrieved for the appropriate name space to use, so I've just replaced the variable ns with the actual name space.
I get exactly the same warning on the web service as before (cannot handle HTTP method: OPTIONS) and in the browser's error console I get the error "document is null". When I log the value of req.responseXML in soapclient.js I see that it is null.
Could anyone advise on what might be going wrong and what I should do to get this to work?
I found out what was going on here. It is the same scenario as in this thread: jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox.
Basically I'm using Firefox and when one is doing a cross domain call (domain of the address of the web service is not the same as the domain of the web page) from Firefox using AJAX, Firefox first sends an OPTIONS HTTP-message (before it transmits the POST message), to determine from the web service if the call should be allowed or not. The web service must then respond to this OPTIONS message to tell if it allows the request to come through.
Now, the warning from JAX-WS ("Cannot handle HTTP method: OPTIONS") suggests that it won't handle any OPTIONS HTTP-messages. That's ok - the web service will eventually run on Glassfish.
The question now is how I can configure Glassfish to respond to the OPTIONS message.
In the thread referenced above Juha says that he uses the following code in Django:
def send_data(request):
if request.method == "OPTIONS":
response = HttpResponse()
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
response['Access-Control-Max-Age'] = 1000
response['Access-Control-Allow-Headers'] = '*'
return response
if request.method == "POST":
# ...
Access-Control-Allow-Origin gives a pattern which indicates which origins (recipient addresses) will be accepted (mine might be a bit more strict than simply allowing any origin) and Access-Control-Max-Age tells after how many seconds the client will have to request permission again.
How do I do this in Glassfish?
Have you actually tested that ws is working properly?
You can use SoapUI for inspecting request/response etc.
When you confirm that ws is working from SoapUI, inspect what is format of raw Soap message. Then try to inspect how it looks before sending with .js method, and compare them.
It might help you understand what is wrong.
Check if this helps
http://bugs.jquery.com/attachment/ticket/6029/jquery-disable-firefox3-cross-domain-magic.patch
it's marked as invalid
http://bugs.jquery.com/ticket/6029
but it might give you some hint
On the other hand, instead to override proper settings for cross-domain scripting might be better if you can create and call local page that will do request to ws and return result.
Or even better, you can create page that will receive url as param and do request to that url and just return result. That way it will be more generic and reusable.

Categories