Java 与 Grizzly 和 Jersey 的 SSL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21098105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:34:01  来源:igfitidea点击:

SSL with Grizzly and Jersey

javarestssljerseygrizzly

提问by user1389906

I'm trying to get grizzly to use SSL encryption and still work fine with Jersey. I've looked all over the Internet, and I find all kinds of different attempts at SSL with Grizzly and Jersey. Seems like there are different ways of doing it depending on which version you are using, and how you decided to implement it. I haven't been able to get any examples to work with my code yet.

我试图让灰熊使用 SSL 加密并且仍然可以在 Jersey 中正常工作。我浏览了整个 Internet,我发现使用 Grizzly 和 Jersey 对 SSL 进行了各种不同的尝试。根据您使用的版本以及您决定实现它的方式,似乎有不同的方法可以做到这一点。我还没有能够得到任何例子来处理我的代码。

Here's how I start up my server:

这是我启动服务器的方法:

static HttpServer startSecureServer() throws IOException{
        ResourceConfig rc=new PackagesResourceConfig("server.grizzlyresources");
        SSLContextConfigurator sslCon=new SSLContextConfigurator();

        sslCon.setKeyStoreFile(ConfigLoader.getKeystoreLocation()); // contains server keypair
        sslCon.setKeyStorePass(ConfigLoader.getKeystorePassword());

        System.out.println("Starting server on port "+ConfigLoader.getHttpsServerPort());
        HttpServer secure=GrizzlyServerFactory.createHttpServer(BASE_URI_SECURED, rc);
        secure.stop();

        HashSet<NetworkListener> lists=new HashSet<NetworkListener>(secure.getListeners());
        for (NetworkListener listener : lists){
            listener.setSecure(true);
            SSLEngineConfigurator ssle=new SSLEngineConfigurator(sslCon);
            listener.setSSLEngineConfig(ssle);
            secure.addListener(listener);
            System.out.println(listener);
        }

        secure.start();
        return secure;
}

private static URI getBaseURISecured(){
    return UriBuilder.fromUri("https://0.0.0.0/").port(ConfigLoader.getHttpsServerPort()).build();
}

private static final URI BASE_URI_SECURED = getBaseURISecured();

ConfigLoader loads in information from a config file. When I run this code, it starts up the server, it finds the resources in the server.grizzlyresources package, and it works great! Except for one thing. The server isn't secured. I can telnet into it and send an HTTP request in plain text for one of my resources, and it will return it. So the code works for starting up the server, but the whole SSL part of it is just being bypassed. Any ideas how to fix this or why it might be doing this?

ConfigLoader 从配置文件加载信息。当我运行这段代码时,它会启动服务器,它会在 server.grizzlyresources 包中找到资源,而且效果很好!除了一件事。服务器不安全。我可以 telnet 进入它并以纯文本形式为我的一个资源发送一个 HTTP 请求,它会返回它。因此该代码可用于启动服务器,但它的整个 SSL 部分都被绕过了。任何想法如何解决这个问题或为什么它可能会这样做?

Here's the output to the console when I run it:

这是我运行时控制台的输出:

Starting server on port 9999
Jan 13, 2014 9:51:08 AM com.sun.jersey.api.core.PackagesResourceConfig init
INFO: Scanning for root resource and provider classes in the packages:
  server.grizzlyresources
Jan 13, 2014 9:51:08 AM com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
  class server.grizzlyresources.SessionResource
  class server.grizzlyresources.LoginResource
Jan 13, 2014 9:51:08 AM com.sun.jersey.api.core.ScanningResourceConfig init
INFO: No provider classes found.
Jan 13, 2014 9:51:08 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
INFO: Initiating Jersey application, version 'Jersey: 1.12 02/15/2012 04:51 PM'
Jan 13, 2014 9:51:09 AM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [0.0.0.0:9999]
Jan 13, 2014 9:51:09 AM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.
Jan 13, 2014 9:51:09 AM org.glassfish.grizzly.http.server.NetworkListener stop
INFO: Stopped listener bound to [0.0.0.0:9999]
NetworkListener{name='grizzly', host='0.0.0.0', port=9999, secure=true}
Jan 13, 2014 9:51:09 AM org.glassfish.grizzly.http.server.NetworkListener start
INFO: Started listener bound to [0.0.0.0:9999]
Jan 13, 2014 9:51:09 AM org.glassfish.grizzly.http.server.HttpServer start
INFO: [HttpServer] Started.

I'm using Grizzly 2.2.1, and Jersey 1.12.

我使用的是 Grizzly 2.2.1 和 Jersey 1.12。

Thanks a bunch!

谢谢一堆!

采纳答案by alexey

IMO you can use different Factory method to initialize secured Grizzly HttpServer:

IMO 您可以使用不同的工厂方法来初始化安全的 Grizzly HttpServer:

HttpServer secure = GrizzlyServerFactory.createHttpServer(BASE_URI_SECURED,
                        ContainerFactory.createContainer(HttpHandler.class, rc),
                        true,
                        new SSLEngineConfigurator(sslCon));

If you initialize the server like this, you don't need to stop and reconfigure it again.

如果像这样初始化服务器,则不需要再次停止并重新配置它。

Hope this will help.

希望这会有所帮助。

回答by Daniel Nuriyev

I have a nice and tested example using Grizzly 2.3.3 in: https://github.com/danielnuriyev/scriptedstuff/tree/master/src/com/scriptedstuff/server

我有一个使用 Grizzly 2.3.3 的不错且经过测试的示例:https: //github.com/danielnuriyev/scriptedstuff/tree/master/src/com/scriptedstuff/server

回答by Wolfgang Fahl

The following code works with Grizzly 2.3.7 and I am using Jersey 1.18 - this includes code for SSL Client Authentication - if you don't have the keystores this feature will simply be ignored.

以下代码适用于 Grizzly 2.3.7,我使用的是 Jersey 1.18 - 这包括 SSL 客户端身份验证的代码 - 如果您没有密钥库,此功能将被忽略。

/**
 * create a Server based on an url and possibly a ResourceConfig
 * 
 * @param url
 * @param rc
 * @param secure
 *          - true if SSL should be used
 * @param contextPath 
 * @return
 * @throws Exception
 */
public HttpServer createHttpServer(String url, ResourceConfig rc,
        boolean secure, String contextPath) throws Exception {
    // HttpServer result = GrizzlyServerFactory.createHttpServer(url, rc);
    // http://grepcode.com/file/repo1.maven.org/maven2/com.sun.jersey/jersey-grizzly2/1.6/com/sun/jersey/api/container/grizzly2/GrizzlyServerFactory.java#GrizzlyServerFactory.createHttpServer%28java.net.URI%2Ccom.sun.jersey.api.container.grizzly2.ResourceConfig%29
    HttpServer result = new HttpServer();
    final NetworkListener listener = new NetworkListener("grizzly",
            settings.getHost(), settings.getPort());
    result.addListener(listener);
    // do we need SSL?
    if (secure) {
        listener.setSecure(secure);
        SSLEngineConfigurator sslEngineConfigurator = createSSLConfig(true);
        listener.setSSLEngineConfig(sslEngineConfigurator);
    }
    // Map the path to the processor.
    final ServerConfiguration config = result.getServerConfiguration();
    final HttpHandler handler = ContainerFactory.createContainer(
            HttpHandler.class, rc);
    config.addHttpHandler(handler, contextPath);
    return result;
}

  /**
 * create SSL Configuration
 * 
 * @param isServer
 *          true if this is for the server
 * @return
 * @throws Exception
 */
private SSLEngineConfigurator createSSLConfig(boolean isServer)
        throws Exception {
    final SSLContextConfigurator sslContextConfigurator = new SSLContextConfigurator();
    // override system properties
    final File cacerts = getStoreFile("server truststore",
            "truststore_server.jks");
    if (cacerts != null) {
        sslContextConfigurator.setTrustStoreFile(cacerts.getAbsolutePath());
        sslContextConfigurator.setTrustStorePass(TRUSTSTORE_PASSWORD);
    }

    // override system properties
    final File keystore = getStoreFile("server keystore", "keystore_server.jks");
    if (keystore != null) {
        sslContextConfigurator.setKeyStoreFile(keystore.getAbsolutePath());
        sslContextConfigurator.setKeyStorePass(TRUSTSTORE_PASSWORD);
    }

    //
    boolean clientMode = false;
    // force client Authentication ...
    boolean needClientAuth = settings.isNeedClientAuth();
    boolean wantClientAuth = settings.isWantClientAuth();
    SSLEngineConfigurator result = new SSLEngineConfigurator(
            sslContextConfigurator.createSSLContext(), clientMode, needClientAuth,
            wantClientAuth);
    return result;
}

回答by user1389906

Sorry to take so long to post this up here. Alexey's answer led me to the working solution, which is a lot like Wolfgang Fahl's code. Here's what I ended up with:

很抱歉花了这么长时间才把这个贴在这里。Alexey 的回答让我找到了工作解决方案,它很像 Wolfgang Fahl 的代码。这是我的结果:

static HttpServer startSecureServer() throws IOException
{
    System.out.println("Starting server on port " + ConfigLoader.getHttpsServerPort());
    ResourceConfig rc = new PackagesResourceConfig("com.kinpoint.server.grizzlyresources");

    SSLContextConfigurator sslCon = new SSLContextConfigurator();

    sslCon.setKeyStoreFile(ConfigLoader.getKeystoreLocation()); // contains server keypair
    sslCon.setKeyStorePass(ConfigLoader.getKeystorePassword());

    HttpHandler hand = ContainerFactory.createContainer(HttpHandler.class, rc);

    HttpServer secure = GrizzlyServerFactory.createHttpServer(BASE_URI_SECURED, hand, true,
            new SSLEngineConfigurator(sslCon, false, false, false));

    return secure;
}

The second parameter in the SSLEngineConfigurator tells it not to use client mode. That was what was messing me up. Thanks for the help.

SSLEngineConfigurator 中的第二个参数告诉它不要使用客户端模式。这就是让我搞砸的原因。谢谢您的帮助。