安全Grizzly HttpServer(HTTPS)

时间:2017-01-28 21:58:31

标签: java rest ssl jersey grizzly

目前我在使用HTTPS运行Grizzly Server时遇到问题。我和泽西岛一起使用它。

Grizzly Version是:2.3.23

泽西岛版本:2.24.1

以下是启动服务器的方法:

public class Main {
public static final String BASE_URI = "https://localhost:8443/api/";
private static final String KEYSTORE_LOC = "I:\\rest-api\\keystore";
//private static final String KEYSTORE_LOC = "./server.cert";
private static final String KEYSTORE_PASS= "somepw123";

public static HttpServer startServer() {

    final ResourceConfig rc = new ResourceConfig()
            .register(MultiPartFeature.class)
            .packages("com.restapi");


    SSLContextConfigurator sslCon = new SSLContextConfigurator();

    sslCon.setKeyStoreFile(KEYSTORE_LOC);
    sslCon.setKeyStorePass(KEYSTORE_PASS);

    return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc, true,new SSLEngineConfigurator(sslCon).setClientMode(false).setNeedClientAuth(false));
}

密钥库文件是使用keytool生成的

keytool -genkey -keystore ./keystore -alias serverKey -dname

当我尝试打开网址时,我的浏览器会告诉我

  

localhost意外关闭了连接

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

通过添加Truststore文件解决了这个问题。

代码现在看起来像这样:

public class Main {
public static final String BASE_URI = "https://localhost:8443/api/";
private static final String KEYSTORE_LOC = "./keystore_server";
private static final String KEYSTORE_PASS= "keystorePass";

private static final String TRUSTSTORE_LOC = "./truststore_server";
private static final String TRUSTSTORE_PASS = "truststorePass";

private static HttpServer startServer() {

    final ResourceConfig rc = new ResourceConfig()
            .register(MultiPartFeature.class)
            .packages("com.restapi");


    SSLContextConfigurator sslCon = new SSLContextConfigurator();

    sslCon.setKeyStoreFile(KEYSTORE_LOC);
    sslCon.setKeyStorePass(KEYSTORE_PASS);

    sslCon.setTrustStoreFile(TRUSTSTORE_LOC);
    sslCon.setTrustStorePass(TRUSTSTORE_PASS);

    return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc, true,new SSLEngineConfigurator(sslCon).setClientMode(false).setNeedClientAuth(false));
}

使用以下命令创建的密钥和信任库文件:

keytool -genkey -keyalg RSA -keystore ./keystore_client -alias clientKey
keytool -export -alias clientKey -rfc -keystore ./keystore_client > ./client.cert
keytool -import -alias clientCert -file ./client.cert -keystore ./truststore_server

keytool -genkey -keyalg RSA -keystore ./keystore_server -alias serverKey
keytool -export -alias serverKey -rfc -keystore ./keystore_server > ./server.cert
keytool -import -alias serverCert -file ./server.cert -keystore ./truststore_client