CXF SSL configuration for consuming SOAP webservice - apache

Overview
I am going to set SSL configuration for calling a SOAP webservice.
Certificate info:
Certificate file: sureft.p12
Password: sureft
CXF configuration file (cxf.xml):
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sec="http://cxf.apache.org/configuration/security"
xmlns:http="http://cxf.apache.org/transports/http/configuration"
xmlns:jaxws="http://java.sun.com/xml/ns/jaxws" xmlns:cxf="http://www.springframework.org/schema/c"
xsi:schemaLocation="
http://cxf.apache.org/configuration/security
http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/transports/http/configuration
http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<http:conduit name="{http://tmr.qld.gov.au/srvc/getregistrationstatus/v2_0}GetRegistrationStatusPort.http-conduit">
<http:tlsClientParameters>
<sec:keyManagers keyPassword="sureft">
<sec:keyStore type="pksc12" password="sureft"
file="keystore/sureft.p12"/>
</sec:keyManagers>
</http:tlsClientParameters>
<http:client AutoRedirect="true" Connection="Keep-Alive"/>
</http:conduit>
</beans>
Issue
However, when the webservice invoked it throws 403:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.sun.xml.internal.ws.client.ClientTransportException: The server sent HTTP status code 403: Forbidden
I had a look on http://cxf.apache.org/docs/client-http-transport-including-ssl-support.html but I couldn't solve the isse.
Now I would be grateful if anyone can help me find solution for this problem.
Update Level 1:
I did the following changes but again 403 raised:
. Creating truststore:
Export Create cer file with name myCert.cer from sureft.p12
Create truststore certificate with name of myTruststore.jks by running: keytool -import -file myCert.cer -alias firstCA -keystore myTrustStore.jks
Changing cxf.xml file as follows to add truststore:
...
<http:tlsClientParameters>
<sec:keyManagers keyPassword="sureft">
<sec:keyStore type="pkcs12" password="sureft"
file="keystore/sureft.p12"/>
</sec:keyManagers>
<sec:trustManagers>
<sec:keyStore type="JKS" password="123456"
file="keystore/myTrustStore.jks"/>
</sec:trustManagers>
</http:tlsClientParameters>
...
Update Level 2
I changed my code as following and the 403 solved but another issue raised:
#RequestMapping(method = RequestMethod.GET)
public void getBillInfo2(String plateNumber) {
QName qname = new QName("http://testURL/srvc/getregistrationstatus/v2_0/", "GetRegistrationStatusService");
URL wsdl = getClass().getResource("wsdl/test.getregistrationstatus.v2_0.wsdl");
GetRegistrationStatusService service = new GetRegistrationStatusService(wsdl, qname);
GetRegistrationStatus registrationStatus = service.getPort(qname, GetRegistrationStatus.class);
Client client = ClientProxy.getClient(registrationStatus);
HTTPConduit http = (HTTPConduit) client.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(32000);
httpClientPolicy.setContentType("application/soap+xml; charset=utf-8");
http.setClient(httpClientPolicy);
GetRegistrationStatusRequest request = new GetRegistrationStatusRequest();
request.setPlateNo(plateNumber);
GetRegistrationStatusResponse result = registrationStatus.execute(request);
log.debug(result.toString());
}
The Exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.xml.ws.soap.SOAPFaultException: Fault string, and possibly fault code, not set
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:980)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:859)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:844)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.ShallowEtagHeaderFilter.doFilterInternal(ShallowEtagHeaderFilter.java:87)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at com.blss.trails.registration.RegistrationSearchInvocationTest.test(RegistrationSearchInvocationTest.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: javax.xml.ws.soap.SOAPFaultException: Fault string, and possibly fault code, not set
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)
at com.sun.proxy.$Proxy104.execute(Unknown Source)
at com.blss.trails.registration.RegistrationSearchInvocation.getBillInfo2(RegistrationSearchInvocation.java:72)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968)
... 46 more
Caused by: java.lang.NullPointerException
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.createConnection(URLConnectionHTTPConduit.java:104)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit.setupConnection(URLConnectionHTTPConduit.java:117)
at org.apache.cxf.transport.http.HTTPConduit.prepare(HTTPConduit.java:497)
at org.apache.cxf.interceptor.MessageSenderInterceptor.handleMessage(MessageSenderInterceptor.java:46)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:514)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:423)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:324)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:277)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
... 61 more
Any help would be highly appreciated.

I did the following steps and the problem solved:
Exporting publickey certificate from p12 certificate
Adding it as truststore to my jre cacerts (More info for importing the truststore can be fount in How to solve javax.net.ssl.SSLHandshakeException Error?):
.
keytool -import -file <the cert file> -alias <some meaningful name> keystore <path to cacerts file>
.
Modifying the code as follows:
...
#RequestMapping(method = RequestMethod.GET, path = "/billinfo")
public void getBillInfo(String plateNumber) {
QName qname = new QName("http://tmr.qld.gov.au/srvc/getregistrationstatus/v2_0/", "GetRegistrationStatusService");
URL wsdl = getClass().getResource("wsdl/myWSDL.wsdl");
GetRegistrationStatusService service = new GetRegistrationStatusService(wsdl, qname);
service.addPort(qname, SOAPBinding.SOAP12HTTP_BINDING, "https://myurl/getregistrationstatus_v2_0/");
GetRegistrationStatus registrationStatus = service.getPort(qname, GetRegistrationStatus.class);
Client cxfClient = ClientProxy.getClient(registrationStatus);
cxfClient.getInInterceptors().add(new LoggingInInterceptor());
cxfClient.getOutInterceptors().add(new LoggingOutInterceptor());
cxfClient.getOutFaultInterceptors().add(new FaultOutInterceptor());
HTTPConduit httpConduit = (HTTPConduit) cxfClient.getConduit();
HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
httpClientPolicy.setConnectionTimeout(36000);
httpClientPolicy.setAllowChunking(false);
httpClientPolicy.setReceiveTimeout(32000);
httpClientPolicy.setContentType("application/soap+xml;charset=utf-8");
httpConduit.setClient(httpClientPolicy);
//Keystore setting
try {
final TLSClientParameters tlsCP = new TLSClientParameters();
File p12File = new File("sureft.p12");
KeyStore.Builder builder = KeyStore.Builder.newInstance("PKCS12", null, p12File, new KeyStore.PasswordProtection("sureft".toCharArray()));
KeyStore keyStore = builder.getKeyStore();
String keyPassword = "sureft";
final KeyManager[] myKeyManagers = getKeyManagers(keyStore, keyPassword);
tlsCP.setKeyManagers(myKeyManagers);
httpConduit.setTlsClientParameters(tlsCP);
} catch (Exception e) {
e.printStackTrace();
}
GetRegistrationStatusRequest request = new GetRegistrationStatusRequest();
request.setPlateNo(plateNumber);
GetRegistrationStatusResponse result = registrationStatus.execute(request);
log.debug("Result: " + result.toString());
}
private static KeyManager[] getKeyManagers(KeyStore keyStore, String keyPassword) throws GeneralSecurityException, IOException {
String alg = KeyManagerFactory.getDefaultAlgorithm();
char[] keyPass = keyPassword != null ? keyPassword.toCharArray() : null;
KeyManagerFactory fac = KeyManagerFactory.getInstance(alg);
fac.init(keyStore, keyPass);
return fac.getKeyManagers();
}
...
This was my solution but I would be grateful if anyone could share their solutions here.

Related

CentOS7, KeyStore is N/A while connecting to LDAPS server in Tomcat 8

Environment:
CentOS 7
java-1.8.0-openjdk-1.8.0.292.b10-1.el7_9.x86_64
Tomcat 8.5.63 + self-signed SSL certificate
osixia/docker-openldap + official SSL certificate
Set --env LDAP_TLS_VERIFY_CLIENT=never to skip client certificate validation.
Had been LDAPS login successfully by using ApacheDirectoryStudio and Gawor_ldapbrowser.
I have a server API which run with Tomcat 8, and will connect to an OpenLDAP server via ldaps protocol.
My code is simple as:
LdapContext ctx = null;
try
{
Hashtable<String, String> env = getLDAPBase(this.searcher, this.searcherPwd, this.ldapUrl);
ctx = new InitialLdapContext(env, null); // line 689
return findUserIdInLdap(userid, ctx);
}
public static Hashtable<String, String> getLDAPBase(String ldapUserName, String pwd, String ldapUrl)
{
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, ldapUserName);
env.put(Context.SECURITY_CREDENTIALS, pwd);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapUrl);
return env;
}
The API log:
2021/06/02 14:02:55.168,[05863d2e-5ca6-43bb-bd18-3c10689bdcbf]05863d2e-5ca6-43bb-bd18-3c10689bdcbf, userid=test1_LDAP,searchBase=dc=my,dc=com,FILTER_STR=(&(|(sAMAccountName={0})(cn={0})(uid={0}))(objectClass=*))
javax.naming.CommunicationException: q2ldap.my.com:6362 [Root exception is java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)]
at com.sun.jndi.ldap.Connection.<init>(Connection.java:233)
at com.sun.jndi.ldap.LdapClient.<init>(LdapClient.java:137)
at com.sun.jndi.ldap.LdapClient.getInstance(LdapClient.java:1615)
at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2849)
at com.sun.jndi.ldap.LdapCtx.<init>(LdapCtx.java:347)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxFromUrl(LdapCtxFactory.java:225)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:189)
at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:243)
at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:154)
at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:84)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:695)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:313)
at javax.naming.InitialContext.init(InitialContext.java:244)
at javax.naming.ldap.InitialLdapContext.<init>(InitialLdapContext.java:154)
at com.my.OpenLdapAuthenticator.getUserIdInLdap(OpenLdapAuthenticator.java:689)
at com.my.OpenLdapAuthenticator.authenticationFlow(OpenLdapAuthenticator.java:108)
at com.my.LdapAuthManager.authenticate(LdapAuthManager.java:247)
at com.my.ServletPrivateCloudAAA.processRequest(ServletPrivateCloudAAA.java:147)
at com.my.http.api.StaxAPIServlet.doProcess(StaxAPIServlet.java:346)
at com.my.http.api.StaxAPIServlet.service(StaxAPIServlet.java:107)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.my.api.aaa.LockIpFilter.doFilter(LockIpFilter.java:95)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.my.api.aaa.AccessLogFilter.doFilter(AccessLogFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.filters.CorsFilter.handleNonCORS(CorsFilter.java:363)
at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:169)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:186)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:544)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:353)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:616)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:831)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1629)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
at javax.net.ssl.DefaultSSLSocketFactory.throwException(SSLSocketFactory.java:248)
at javax.net.ssl.DefaultSSLSocketFactory.createSocket(SSLSocketFactory.java:262)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.jndi.ldap.Connection.createSocket(Connection.java:345)
at com.sun.jndi.ldap.Connection.<init>(Connection.java:220)
... 51 more
Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: Default, provider: SunJSSE, class: sun.security.ssl.SSLContextImpl$DefaultSSLContext)
at java.security.Provider$Service.newInstance(Provider.java:1617)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:236)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:164)
at javax.net.ssl.SSLContext.getInstance(SSLContext.java:156)
at javax.net.ssl.SSLContext.getDefault(SSLContext.java:96)
at javax.net.ssl.SSLSocketFactory.getDefault(SSLSocketFactory.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.sun.jndi.ldap.Connection.createSocket(Connection.java:301)
... 52 more
Caused by: java.security.PrivilegedActionException: java.io.FileNotFoundException: N/A (No such file or directory)
at java.security.AccessController.doPrivileged(Native Method)
at sun.security.ssl.SSLContextImpl$DefaultManagersHolder.getKeyManagers(SSLContextImpl.java:1095)
at sun.security.ssl.SSLContextImpl$DefaultManagersHolder.<clinit>(SSLContextImpl.java:1021)
at sun.security.ssl.SSLContextImpl$DefaultSSLContext.<init>(SSLContextImpl.java:1186)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.security.Provider$Service.newInstance(Provider.java:1595)
... 62 more
Caused by: java.io.FileNotFoundException: N/A (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at sun.security.ssl.SSLContextImpl$DefaultManagersHolder$2.run(SSLContextImpl.java:1099)
at sun.security.ssl.SSLContextImpl$DefaultManagersHolder$2.run(SSLContextImpl.java:1096)
... 71 more
After added -Djava.net.debug=all, I found below in log:
javax.net.ssl|FINE|03 11|https-jsse-nio-443-exec-12|2021-06-02 16:04:37.612 CST|SSLContextImpl.java:1076|keyStore is : N/A
javax.net.ssl|FINE|03 11|https-jsse-nio-443-exec-12|2021-06-02 16:04:37.613 CST|SSLContextImpl.java:1077|keyStore type is : pkcs12
javax.net.ssl|FINE|03 11|https-jsse-nio-443-exec-12|2021-06-02 16:04:37.613 CST|SSLContextImpl.java:1079|keyStore provider is :
javax.net.ssl|FINE|03 11|https-jsse-nio-443-exec-12|2021-06-02 16:04:37.671 CST|SSLEngineOutputRecord.java:266|WRITE: TLS12 application_data, length = 404
I have no idea why there is a N/A keyStore.
CentOS 7 has no default openjdk 9 to install, so I installed openjdk 11, then call my API again.
And the API connected via LDAPS successfully with log:
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.895 CST|SSLContextImpl.java:1088|keyStore is :
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.896 CST|SSLContextImpl.java:1089|keyStore type is : pkcs12
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.896 CST|SSLContextImpl.java:1091|keyStore provider is :
javax.net.ssl|ALL|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.896 CST|SSLContextImpl.java:1126|init keystore
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.896 CST|SSLContextImpl.java:1149|init keymanager of type SunX509
javax.net.ssl|ALL|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.897 CST|SSLContextImpl.java:115|trigger seeding of SecureRandom
javax.net.ssl|ALL|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:14.897 CST|SSLContextImpl.java:119|done seeding of SecureRandom
javax.net.ssl|DEBUG|03 08|https-jsse-nio-443-exec-13|2021-06-01 14:09:15.091 CST|SSLSocketOutputRecord.java:309|WRITE: TLS12 application_data, length = 52
But I can't just upgrade the JRE version to solve the problem because our server APIs are compatible only with Java 8.
So upgrading Java version, eg. 11, is not our option in short term.
Is there any hints or suggestions to solve this problem?
Thank you in advance.

java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory while running as Junit

While trying to run my Karate project as Junit, I am getting the below error.
All of my slf4j dependencies in the .m2 repo looks fine. But couldn't figure out what is the issue. Could you please someone help me to get rid of this issue
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at com.intuit.karate.Runner.<clinit>(Runner.java:51)
at soa.core.ParallelTest.testParallel(ParallelTest.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 25 more
Here is my Junit Runner class. The exception is thrown at line number 2 of testParallel() method
public class ParallelTest {
#Test
public void testParallel() {
System.setProperty("karate.env", "acpt");
Results results = Runner.parallel(getClass(), 1);
generateReport(results.getReportDir());
assertTrue(results.getErrorMessages(), results.getFailCount() == 0);
}
public static void generateReport(String karateOutputPath) {
Collection<File> jsonFiles = FileUtils.listFiles(new File(karateOutputPath), new String[] {"json"}, true);
List<String> jsonPaths = new ArrayList(jsonFiles.size());
jsonFiles.forEach(file -> jsonPaths.add(file.getAbsolutePath()));
Configuration config = new Configuration(new File("target"), "WTR_EPP");
ReportBuilder reportBuilder = new ReportBuilder(jsonPaths, config);
reportBuilder.generateReports();
}
}
Pretty sure you have a pom.xml that includes a bunch of other dependencies and you will need to resolve JAR / library conflicts yourself.
One suggestion is to create a quickstart project - get that working first - and then compare with the problem project you have.
If you are still stuck - please follow this process: https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

How to use MQTT.fx to connect to IOT central?

I am trying to use MQTT directly to connect to IOT central.
I just followed below documentation,
https://learn.microsoft.com/en-us/azure/iot-central/concepts-connectivity#connect-a-single-device
https://www.instructables.com/id/Azure-IoT-Hub-Set-Up-MQTTfx-Sigfox-Callback-and-Dr/
https://github.com/MediaTek-Labs/aws_mbedtls_mqtt/pull/9/files?short_path=04c6e90
https://docs.azure.cn/zh-cn/articles/azure-operations-guide/iot-hub/aog-iot-hub-howto-connect-with-tool-mqtt-fx (Translate to english)
Above documentation I used dps_cstr tool from github to generate connection string with SAS token from this link
https://learn.microsoft.com/en-us/azure/iot-central/tutorial-add-device#prepare-the-client-code
Broker Address = saas-iothub-947867dc-cd5d-446c-90ff-e0f964f020fe.azure-devices.net
Broker port = 8883
Client ID = 92ff3e25-00e5-4249-9074
User Name = saas-iothub-947867dc-cd5d-446c-90ff.azure-devices.net/92ff3e25-00e5-4249-9074
MQTT Version = 3.1.1
Password = OfAlY0BGstmuinZzOcdDDf
I have configured the MQTT.fx with connection profile for iot central by using above connection string and details.
Attached the snap of that
When i try to connect to this, I am getting an error "Not authorized to connect".
Log:
2018-12-20 00:42:49,738 INFO --- BrokerConnectorController : onConnect
2018-12-20 00:42:49,740 INFO --- ScriptsController : Clear console.
2018-12-20 00:42:49,804 INFO --- MqttFX ClientModel : MqttClient with ID 92ff3e25-00e5-4249-9074-854b43b5a949 assigned.
2018-12-20 00:42:53,571 ERROR --- MqttFX ClientModel : Error when connecting
org.eclipse.paho.client.mqttv3.MqttSecurityException: Not authorized to connect
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:145) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_181]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_181]
2018-12-20 00:42:53,572 ERROR --- MqttFX ClientModel : Please verify your Settings (e.g. Broker Address, Broker Port & Client ID) and the user credentials!
org.eclipse.paho.client.mqttv3.MqttSecurityException: Not authorized to connect
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:28) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at org.eclipse.paho.client.mqttv3.internal.ClientState.notifyReceivedAck(ClientState.java:988) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at org.eclipse.paho.client.mqttv3.internal.CommsReceiver.run(CommsReceiver.java:145) ~[org.eclipse.paho.client.mqttv3-1.2.0.jar:?]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[?:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [?:1.8.0_181]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [?:1.8.0_181]
at java.lang.Thread.run(Unknown Source) [?:1.8.0_181]
2018-12-20 00:42:53,574 INFO --- ScriptsController : Clear console.
2018-12-20 00:42:53,574 ERROR --- BrokerConnectService : Not authorized to connect
EDIT:
I created a CA certificate from https://github.com/Azure/azure-iot-sdk-c/blob/master/certs/certs.c as CACert.cer
I selected CS Certificate file option in SSL/TLS option and tried again.
But i have got the same error
I have just finished a test using a MQTT.fx client connected to the Azure IoT Central.
Based on the doc Using the MQTT protocol directly the password must be in the following format, see example:
SharedAccessSignature sr={your hub name}.azure-devices.net%2Fdevices%2FMyDevice01%2Fapi-version%3D2016-11-14&sig=vSgHBMUG.....Ntg%3d&se=1456481802
You have to generate the above password (sas token) string. You can use the following helper function:
string sasToken = SharedAccessSignatureBuilder.GetSASTokenFromConnectionString(connectionString);
public sealed class SharedAccessSignatureBuilder
{
public static string GetHostNameNamespaceFromConnectionString(string connectionString)
{
return GetPartsFromConnectionString(connectionString)["HostName"].Split('.').FirstOrDefault();
}
public static string GetSASTokenFromConnectionString(string connectionString, uint hours = 24)
{
var parts = GetPartsFromConnectionString(connectionString);
return GetSASToken(parts["HostName"], parts["SharedAccessKey"], parts.Keys.Contains("SharedAccessKeyName") ? parts["SharedAccessKeyName"] : null, hours);
}
public static string GetSASToken(string resourceUri, string key, string keyName = null, uint hours = 24)
{
var expiry = GetExpiry(hours);
string stringToSign = System.Web.HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
HMACSHA256 hmac = new HMACSHA256(Convert.FromBase64String(key));
var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry);
if(!string.IsNullOrEmpty(keyName))
sasToken += String.Format(CultureInfo.InvariantCulture, "&skn={0}", keyName);
return sasToken;
}
#region Helpers
private static Dictionary<string, string> GetPartsFromConnectionString(string connectionString)
{
return connectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(new[] { '=' }, 2)).ToDictionary(x => x[0].Trim(), x => x[1].Trim());
}
// default expiring = 24 hours
private static string GetExpiry(uint hours = 24)
{
TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
return Convert.ToString((int)sinceEpoch.TotalSeconds + 3600 * hours);
}
#endregion
}
The following screen snippets show the MQTT.fx device (myfirstdevice) connected to the Azure IoT Central and the device Dashboard.

Jetty HttpClientTransportOverHTTP2 with SSL

I am trying to make a simple GET request using Jetty's HttpClientTransportOverHTTP2, but it fails. Here is my code:
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.http2.client.HTTP2Client;
import org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2;
import org.eclipse.jetty.util.ssl.SslContextFactory;
public class JettyClientExample {
public static void main(String[] args) throws Exception {
HttpClientTransportOverHTTP2 clientTransport = new HttpClientTransportOverHTTP2(new HTTP2Client());
HttpClient client = new HttpClient(clientTransport, new SslContextFactory(true));
client.start();
ContentResponse response = client.GET("https://http2.akamai.com");
System.out.println("Version: " + response.getVersion());
System.out.println("Status: " + response.getStatus());
System.out.println("Content: " + response.getContentAsString());
}
}
And here is the Exception I get in the line client.GET("https://http2.akamai.com")
Exception in thread "main" java.util.concurrent.ExecutionException: java.nio.channels.ClosedChannelException
at org.eclipse.jetty.client.util.FutureResponseListener.getResult(FutureResponseListener.java:118)
at org.eclipse.jetty.client.util.FutureResponseListener.get(FutureResponseListener.java:101)
at org.eclipse.jetty.client.HttpRequest.send(HttpRequest.java:653)
at org.eclipse.jetty.client.HttpClient.GET(HttpClient.java:343)
at org.eclipse.jetty.client.HttpClient.GET(HttpClient.java:328)
at de.consol.labs.h2c.examples.client.okhttp.JettyClientExample.main(JettyClientExample.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.nio.channels.ClosedChannelException
at org.eclipse.jetty.http2.HTTP2Session.onShutdown(HTTP2Session.java:779)
at org.eclipse.jetty.http2.HTTP2Connection$HTTP2Producer.produce(HTTP2Connection.java:181)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:162)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.execute(ExecuteProduceConsume.java:101)
at org.eclipse.jetty.http2.HTTP2Connection.onOpen(HTTP2Connection.java:80)
at org.eclipse.jetty.http2.client.HTTP2ClientConnectionFactory$HTTP2ClientConnection.onOpen(HTTP2ClientConnectionFactory.java:105)
at org.eclipse.jetty.io.ssl.SslConnection.onOpen(SslConnection.java:152)
at org.eclipse.jetty.io.ClientConnectionFactory$Helper.open(ClientConnectionFactory.java:70)
at org.eclipse.jetty.io.ClientConnectionFactory$Helper.replaceConnection(ClientConnectionFactory.java:63)
at org.eclipse.jetty.io.NegotiatingClientConnection.replaceConnection(NegotiatingClientConnection.java:113)
at org.eclipse.jetty.io.NegotiatingClientConnection.onFillable(NegotiatingClientConnection.java:89)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:245)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.ssl.SslConnection.onFillable(SslConnection.java:192)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:245)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
at java.lang.Thread.run(Thread.java:745)
I am using version 9.3.3.v20150827, and I put the ALPN JAR into my boot classpath with -Xbootclasspath/p:<path>.
For some reason, I didn't find any working example of HttpClientTransportOverHTTP2 with SSL on the Internet.
What am I missing?
You hit this bug, which is fixed in Jetty 9.3.4.

JIRA Rest API change issue status --> 401 error

I'm trying to change the status of a Jira Issue with the Rest API, as described here: https://docs.atlassian.com/jira/REST/6.3-m01-1/
I post to the URL
XXXXXX/rest/api/latest/issue/Project-Key/transitions?expand=transitions.fields
However, it doesn't work :(, I get a an 401 error (unauthorized), even though i authenticate like described in the atlassian documentation. (user used to authenticate has the permission to change the status)
client.addFilter(new HTTPBasicAuthFilter("username", "password"));
WebResource webResource = client.resource(getDestination());
Though, get request works fine an returns:
{
"expand": "transitions",
"transitions": [{
"id": "961",
"name": "Deploybar",
"to": {
"self": "https://issues.xxxxxxxxx.local/jira/rest/api/2/status/10009",
"description": "",
"iconUrl": "https://issues.xxxxxxxxx.local/jira/images/icons/statuses/generic.png",
"name": "Deploybar",
"id": "10009",
"statusCategory": {
"self": "https://issues.xxxxxxxxx.local/jira/rest/api/2/statuscategory/4",
"id": 4,
"key": "indeterminate",
"colorName": "yellow",
"name": "In Arbeit"
}
},
"fields": {
"assignee": {
"required": false,
"schema": {
"type": "user",
"system": "assignee"
},
"name": "Bearbeiter",
"autoCompleteUrl": "https://issues.xxxxxxxxx.local/jira/rest/api/latest/user/assignable/search?issueKey=RCE-98&username=",
"operations": ["set"]
}
}
}
}
Here is how I try to post:
final WebResource webResTransition = jiraTransition.response();
final ClientResponse crTest = webResTransition.accept("application/json").type("application/json").post(ClientResponse.class, {"transition": {"id": "961"}});
My try with Jira Rest Client:
final JerseyJiraRestClientFactory factory = new JerseyJiraRestClientFactory();
final URI jiraServerUri = new URI("https://issues.teamspace.local/rest/api/latest");
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri, "username", "password");
final NullProgressMonitor pm = new NullProgressMonitor();
final Issue issue = restClient.getIssueClient().getIssue("Issue-Key", pm);
Error Message:
com.atlassian.jira.rest.client.RestClientException: com.sun.jersey.api.client.ClientHandlerException: 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 com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.invoke(AbstractJerseyRestClient.java:75)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.getAndParse(AbstractJerseyRestClient.java:80)
at com.atlassian.jira.rest.client.internal.jersey.JerseyIssueRestClient.getIssue(JerseyIssueRestClient.java:113)
at at.racon_linz.jenkins.stash_plugin.test.JiraTest.testClient(JiraTest.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: com.sun.jersey.api.client.ClientHandlerException: 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 com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.executeMethod(DefaultApacheHttpMethodExecutor.java:213)
at com.sun.jersey.client.apache.ApacheHttpClientHandler.handle(ApacheHttpClientHandler.java:175)
at com.sun.jersey.api.client.Client.handle(Client.java:648)
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670)
at com.sun.jersey.api.client.WebResource.get(WebResource.java:191)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient$1.call(AbstractJerseyRestClient.java:84)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.invoke(AbstractJerseyRestClient.java:54)
... 22 more
Caused by: 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 com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1747)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1209)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:135)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:943)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:654)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:100)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at org.apache.commons.httpclient.HttpConnection.flushRequestOutputStream(HttpConnection.java:828)
at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.flushRequestOutputStream(MultiThreadedHttpConnectionManager.java:1565)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2116)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.executeMethod(DefaultApacheHttpMethodExecutor.java:210)
... 28 more
Caused by: 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.validator.PKIXValidator.doBuild(PKIXValidator.java:323)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)
at sun.security.validator.Validator.validate(Validator.java:218)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1188)
... 45 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)
... 51 more
Error without HTTPS
com.atlassian.jira.rest.client.RestClientException: com.sun.jersey.api.client.UniformInterfaceException: Client response status: 302
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.invoke(AbstractJerseyRestClient.java:70)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.getAndParse(AbstractJerseyRestClient.java:80)
at com.atlassian.jira.rest.client.internal.jersey.JerseyIssueRestClient.getIssue(JerseyIssueRestClient.java:113)
at at.racon_linz.jenkins.stash_plugin.test.JiraTest.testClient(JiraTest.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:176)
at junit.framework.TestCase.runBare(TestCase.java:141)
at junit.framework.TestResult$1.protect(TestResult.java:122)
at junit.framework.TestResult.runProtected(TestResult.java:142)
at junit.framework.TestResult.run(TestResult.java:125)
at junit.framework.TestCase.run(TestCase.java:129)
at junit.framework.TestSuite.runTest(TestSuite.java:255)
at junit.framework.TestSuite.run(TestSuite.java:250)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:84)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: com.sun.jersey.api.client.UniformInterfaceException: Client response status: 302
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:676)
at com.sun.jersey.api.client.WebResource.get(WebResource.java:191)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient$1.call(AbstractJerseyRestClient.java:84)
at com.atlassian.jira.rest.client.internal.jersey.AbstractJerseyRestClient.invoke(AbstractJerseyRestClient.java:54)
... 22 more
I tried everything I found about this topic, but nothing was working :(
First thing you might want to do is export the JIRA certificate and try to add it to your local Java JRE/JDK installation directory using KeyTool import command :
keytool -importcert -file "C:\Users***\Desktop\JIRA.crt" -keystore
"C:\Program Files (x86)\Java\jdk\jre\lib\security\cacerts"
-storepass ***** -alias Jira
Once you are done with that, try to run your client service and see if the issue goes away.
If not then worst case scenario is that, you can by pass the client service cert validation by passing TrustManager object within sslContext.init(null, trustAllCerts, new SecureRandom()). Please see below for more detail implementation.
private TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
java.security.cert.X509Certificate[] chck = null;
return chck;
}
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
}
} };
sslConfig = SslConfigurator.newInstance().trustStoreFile(trustStoreFile).trustStorePassword(trustStorePassword);
// sslContext = sslConfig.createSSLContext();
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
;
basicAuth = HttpAuthenticationFeature.basic(username, userPassword);
clientConfig = new DefaultClientConfig();
JacksonJsonProvider jacksonJsonProvider = new JacksonJsonProvider().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
clientConfig.getSingletons().add(jacksonJsonProvider);
client = Client.create(clientConfig);
client.addFilter(new HTTPBasicAuthFilter(username, userPassword));
webResource = client.resource(uri);