使用javax.xml.ws.Endpoint实现HTTPS

10

我正在开发一个控制建筑物灯光和供暖的项目。后端(用Java编写)将在Mac Mini上运行,并应通过SOAP访问。

我希望将这个项目的复杂性尽量降到最低,因为我不想要求每个人都必须设置应用服务器来使用它。因此,直到现在,我一直在使用javax.xml.ws.Endpoint:

 Endpoint endpoint = Endpoint.create(frontendInterface);
 String uri = "http://"+config.getHost()+":"+config.getPort()+config.getPath();

 endpoint.publish(uri);

这个代码非常出色(嘿,你上次看到Java只用3行代码就能工作了吗?),但现在我正在寻找一种使用HTTPS而不是HTTP的方法。

有没有一种方法可以在不使用应用服务器的情况下实现此目的,或者有没有其他方法来保护此连接?

问候, Marek

1个回答

17

对于服务器:

SSLContext ssl = SSLContext.getInstance("TLS");

KeyManagerFactory keyFactory = KeyManagerFactory                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
KeyStore store = KeyStore.getInstance("JKS");

store.load(new FileInputStream(keystoreFile),keyPass.toCharArray());

keyFactory.init(store, keyPass.toCharArray());


TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

trustFactory.init(store);

ssl.init(keyFactory.getKeyManagers(),
trustFactory.getTrustManagers(), new SecureRandom());

HttpsConfigurator configurator = new HttpsConfigurator(ssl);

HttpsServer httpsServer = HttpsServer.create(new InetSocketAddress(hostname, port), port);

httpsServer.setHttpsConfigurator(configurator);

HttpContext httpContext = httpsServer.createContext(uri);

httpsServer.start();

endpoint.publish(httpContext);

对于客户端,请确保您执行以下操作:

System.setProperty("javax.net.ssl.trustStore", "path");
System.setProperty("javax.net.ssl.keyStore", "password");
System.setProperty("javax.net.ssl.keyStorePassword", "password");
System.setProperty("javax.net.ssl.keyStoreType", "JKS");
//done to prevent CN verification in client keystore
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
   @Override
   public boolean verify(String hostname, SSLSession session) {
     return true;
   }
});

4
不验证主机名(使用此“HostnameVerifier”让所有内容通过)将删除保护通信的重要步骤。不要这样做! - Bruno
2
请注意,HttpsServer.create中的第二个参数是“允许在侦听套接字上排队的传入连接的最大数量”,参见:http://docs.oracle.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpsServer.html - zpon
“uri”变量需要类似于“/contextPath/”或“/”这样的内容。不幸的是,它对我没有起作用。错误消息为上下文未找到处理程序。在jre8上。 - spy
更新,我已经搞定了。当cxf在类路径上时,由于Java SPI更改,这将无法正常工作。 - spy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接