当前位置: 首页 > 面试题库 >

如何编写使用相互ssl身份验证的Java客户端和服务器应用程序?

施兴言
2023-03-14
问题内容

我正在构建两个必须使用SSL双向身份验证进行通信的Java应用程序,我使用此处的说明来创建客户端和服务器证书。
然后我在服务器应用程序中构建了一个webService,如下所示:

@RequestMapping(value="/testssl", method = RequestMethod.POST, produces="application/json", consumes="application/json")
@ResponseBody
public String testSSl(@RequestBody String name) {       
    return = successfully tested;
}

并且我编辑了tomcat server.xml文件以启用SSL,如下所示:

<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
           maxThreads="150" scheme="https" secure="true"
           clientAuth="true" sslProtocol="TLS" 
           keystoreFile="keyStore/server.jks"
           keystorePass="server123" />

并将server.jks放在Tomcat / Jenkins-Tomcat / keystore / server.jks中,
然后我构建了客户端应用程序以使用Spring RestTemplate通过SSL调用此Web服务,如下所示:

Properties props = new Properties();
props.put("javax.net.ssl.trustStore", "D:\\test\\server.jks");
props.put("javax.net.ssl.trustStoreType", "jks");
props.put("javax.net.ssl.trustStorePassword", "server123");

props.put("javax.net.ssl.keyStore", "D:\\test\\client.jks");
props.put("javax.net.ssl.keyStoreType", "jks");
props.put("javax.net.ssl.keyStorePassword", "client123");

props.put("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
props.put("ws.ssl.loose.disableHostnameVerification", "true");

System.setProperties(props);
SSLContext sslcontext = SSLContexts.createDefault();

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
    new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

HttpsURLConnection.setDefaultSSLSocketFactory(sslcontext.getSocketFactory());
CloseableHttpClient httpClient = HttpClientBuilder.create()
    .setSSLSocketFactory(sslsf).build();

org.springframework.http.client.HttpComponentsClientHttpRequestFactory cc = new HttpComponentsClientHttpRequestFactory(httpClient);
RestTemplate rest = new RestTemplate(cc);
String resp = rest.postForObject("https://10.141.0.77:8443/Monim/testssl", "monim", String.class);
System.err.println(resp);

但是当我运行此应用程序时,出现unable to find valid certification path to requested target异常。我试图再次创建证书,但错误仍然存​​在。当我从firefox浏览器请求网址时,An error occurred during a connection to 10.141.0.77:8443. SSL peer cannot verify your certificate. (Error code: ssl_error_bad_cert_alert) 以及使用chrome访问网址时

Error code: ERR_BAD_SSL_CLIENT_AUTH_CERT

这是客户端应用程序的堆栈跟踪

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://10.141.0.77:8443/Monim/testssl":sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is 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 org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:503)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:452)
at org.springframework.web.client.RestTemplate.postForObject(RestTemplate.java:302)
at com.ebs.csh.sva.handler.SOAPMessage.SendingSoapPostMsg(SOAPMessage.java:135)
at com.ebs.csh.sva.handler.SVAHandler.creditSVA(SVAHandler.java:136)
at com.ebs.csh.sva.services.SVAService.creditSVA(SVAService.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.ebs.commons.services.CommonService.processRequest(CommonService.java:276)
at com.ebs.csh.commons.services.CSHService.processRequest(CSHService.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at $Proxy16.processRequest(Unknown Source)
at com.ebs.commons.webServices.CommonWebService.processRequest(CommonWebService.java:80)
at com.ebs.csh.commons.webServices.CSHWebService.processRequest(CSHWebService.java:63)
at com.ebs.csh.sva.webServices.SVAWebService.creditSVA(SVAWebService.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:838)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:541)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:383)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:166)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:288)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
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 sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1836)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1337)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:966)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1262)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1289)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1273)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:261)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:118)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:314)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:357)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:218)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:194)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:85)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:57)
at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:88)
at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:46)
at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:49)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:488)
... 60 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:385)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1319)
... 82 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:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
... 88 more

如何解决此错误。谢谢


问题答案:

在花了很长时间使这项工作完成之后,解决方案如下:
首先,当使用设置属性时,System.put("key", "value")我注意到经过多次尝试后,它没有设置 KeyStore
没有出现在ssl日志中 ,还尝试将属性设置为使用-Djavax.net.ssl.keyStore=""功能的tomcat配置中的参数也不起作用。
所以我KeyStore从这样的阅读InputStream

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream io = new FileInputStream("path/to/jks/file.jks");
    try{
        keystore.load(io, "pass".toCharArray());
    } finally {
        io.close();
    }

并使用相同的先前代码读取TrustStore如下内容:

    KeyStore trustStore= KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream stream = new FileInputStream("path/to/truststore/file.jks");
    try{
        keystore.load(stream, "trusted".toCharArray());
    } finally {
        stream.close();
    }

之后定义SSLContext

SSLContext sslcontext = SSLContexts.custom()
            .loadKeyMaterial(keystore, "keyPassword".toCharArray())
            .loadTrustMaterial(truststore, new TrustSelfSignedStrategy())
            .build();

loadKeyMaterial用来加载keyStore它,它以您的privateKey的密码"keyPassword"作为参数,因此您必须使用密码来保护私钥,当我尝试使用未使用密码加密“受保护”的普通私钥时,出现异常:java.security.UnrecoverableKeyException: Cannot recover key,默认情况下,它与密钥库密码相同,除非您对其进行了更改。
然后创建SSLConnectionSocketFactory并将其作为参数传递给HttpClient..这对我有用:)



 类似资料:
  • 问题内容: 我有以下代码使用SSL将服务器与客户端连接,现在我想添加客户端身份验证: (我有一个服务器密钥库(JCEKS类型)和一个客户端密钥库(JKS类型),服务器使用了一个信任库(证书),在其中我导入了两个证书,因为我也想使用此信任库进行客户端身份验证) 客户代码: 服务器代码: 在此先感谢您的帮助。 编辑:我在服务器端添加此代码: 但是,如果我删除cacerts中的客户端证书,则连接不会给我

  • 我已经浏览了很多帖子和文章,但没有找到一个简单的解决方案,下面我必须实现。 平台:Spring Boot 2。x、 嵌入Tomcat的x(Spring Security 5.x.x) 解决方案:使用许多客户端应用程序和许多最终用户的REST服务。 > 因此,我必须使用一次性令牌对上述应用程序进行身份验证。因此,我计划通过启用和来实现Spring OAuth2。对于每个应用程序客户端,我将生成一个令

  • 我正在尝试为相互身份验证设置ActiveMQ,以便客户端需要证书才能将消息传递给代理。我在代理上创建了一个密钥库和一个信任库,并导出了一个复制到客户端的证书。在客户端,我也做了同样的事情,尽管我使用的是NMS,所以我只使用导出的证书,我将其添加到代理的信任库中。我还将证书添加到另一个本地计算机可信根证书中。 代理的配置如下: ${activemq.base}/conf/login.config $

  • 我无法使Apache CXF客户端grails插件与双向SSL身份验证一起工作。我调用的web服务提供了一个开发环境URL,它不需要双向身份验证,而且一切正常。然而,他们提供的测试环境URL确实需要双向身份验证,我无法使其正常工作。 grails应用程序在Windows服务器上的Tomcat中运行。 我编写了一个独立的Java测试应用程序来测试双向身份验证。我用适当的密钥库、信任库等来调用它,它工

  • 任务:将Kerberos active directory身份验证添加到不安全的报告和数据操作桌面应用程序。此应用程序是。。。 用Stackless Python 2.7编写 使用Twisted进行客户端-服务器交互 客户端编译为exe并在Windows上运行 服务器在Linux(红帽)上运行 目前,我们从用户帐户中提取Windows网络ID(登录名)并传递到服务器,服务器会查找用户配置为具有的权

  • 我正在尝试在两个LAMP服务器之间进行相互ssl身份验证。 我实际上有3台服务器。一个是主服务器,另外两个是对其进行SOAP调用的客户端。 在主客户端和一个客户端上,我安装了Comodo Postive SSL证书。我可以从该客户端连接到主客户端并成功进行SSL身份验证。 在第二个客户端上,我安装了一个Lets加密证书。我从他们的网站上获得了根证书(并使用https://whatsmychainc

  • 我正在使用预装的Visual Studio解决方案开发我的首批OAuth解决方案之一。 不过,同时我也希望我的服务器应用程序拥有“完全访问权限”。他们需要能够获得列表增加多个用户,删除东西等等。 下面是我的问题,我认为这些问题可以很容易地一起回答: 如何管理两个短期令牌(承载令牌?)连同永久令牌(API令牌?) 我在访问级别上有何不同,因此某些方法需要永久令牌? 在同一方法中,我在访问级别上有何不