Demo 下载: testcxf-rest-https.zip
上一篇spring整合cxf开发JSON格式的RESTful风格web service,如果我们想让其支持https访问该怎么办呢?
注:本文只支持服务器端认证,如要要双向认证,请参考cxf 官方samples中的wsdl_first_https和jax_rs_basic_https两个例子。
实现步骤:
-dname 指定distinguished name,感觉就是ldap中的目录结构,虽然tomcat默认的https端口是8443,这个地方也要用localhost而不是localhost:8443,不然会有问题。-storepass指定keystore的密码,因为产生的key以一个.jks文件存放在磁盘上,当我们需要删除其中的某些证书或者导入某个证书时需要使用storepass。
keytool -genkeypair -validity 730 -alias javacoder_cn -keystore javacoder_cn.jks -dname "cn=localhost" -keypass 123456 -storepass 123456
按照提示输入CN,OU,DC的值。
keytool -genkeypair -validity 730 -alias javacoder_cn -keystore clientKeystore.jks -keypass 123456 -storepass 123456
keytool -export -rfc -keystore javacoder_cn.jks -alias javacoder_cn -file MyService.cer -storepass 123456
keytool -import -noprompt -trustcacerts -file MyService.cer -alias javacoder_cn -keystore clientKeystore.jks -storepass 123456
keytool -list -v -keystore clientKeystore.jks
将port=8443的Connector反注释,添加keystoreFile和keystorePass,修改后的Connector为:
1 2 3 4 5 6 |
<Connector SSLEnabled="true" clientAuth="false" keystoreFile="D:/Ted/TEST/testcxf-rest-https/javacoder_cn.jks" keystorePass="123456" maxThreads="150" port="8443" protocol="org.apache.coyote.http11.Http11Protocol" scheme="https" secure="true" sslProtocol="TLS"/> |
三、为客户端添加https支持,参考clientConfig.xml文件
clientConfig.xm文件其实就是一个标准的spring配置文件。在该文件中添加如下内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<http-conf:conduit name="https://localhost:8443/testcxf-rest-https/categoryservice/.*"> <http-conf:tlsClientParameters secureSocketProtocol="TLS"> <sec:keyManagers keyPassword="123456"> <sec:keyStore type="JKS" password="123456" file="clientKeystore.jks" /> </sec:keyManagers> <sec:trustManagers> <sec:keyStore file="clientKeystore.jks" password="123456" type="JKS" /> </sec:trustManagers> <sec:cipherSuitesFilter> <!-- these filters ensure that a ciphersuite with export-suitable or null encryption is used, but exclude anonymous Diffie-Hellman key change as this is vulnerable to man-in-the-middle attacks --> <sec:include>.*_EXPORT_.*</sec:include> <sec:include>.*_EXPORT1024_.*</sec:include> <sec:include>.*_WITH_DES_.*</sec:include> <sec:include>.*_WITH_AES_.*</sec:include> <sec:include>.*_WITH_NULL_.*</sec:include> <sec:exclude>.*_DH_anon_.*</sec:exclude> </sec:cipherSuitesFilter> </http-conf:tlsClientParameters> </http-conf:conduit> |
这个配置要注意的一点是所有的通配符采用标准的正则表达式,".*"表示任意长度的字符串。cipherSuitesFilter配置支持的ssl加密算法,同理,通配符也是标准的正则表达式。详细介绍请参看官方文档Client HTTP Transport (including SSL support)
调用WebClient.create时提供我们的配置文件
// Service instance
WebClient client = WebClient.create(domainAddress, "clientConfig.xml");
如果我们想要让浏览器能访问我们自签名的https服务器,需要将MyService.cer导入浏览器,对于fireforx,如图:
option->Advanced->View Certificates-Import
Comments are closed.