Monday, May 8, 2017

Embedded Jetty server to support https - hard coded Server Parameters

/*
         Create a basic jetty server object without declaring the port. Since
         we are configuring connectors directly we'll be setting ports on
         those connectors.
        */
        Server server = new Server();
        // gracefully shutdown
        server.setStopAtShutdown(true);

        /*
          SSL Context Factory for HTTPS
          SSL requires a certificate so we configure a factory for ssl contents
          with information pointing to what keystore the ssl connection needs
          to know about. Much more configuration is available the ssl context,
          including things like choosing the particular certificate out of a
          keystore to be used.
        */
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
        // Fixed me: password as incoming parameter
        sslContextFactory.setKeyStorePassword("OBF:1sot1v961saj1v9i1v941sar1v9g1sox");

/*
          HTTPS Configuration
          HttpConfiguration is a collection of configuration information
          appropriate for http and https. The default scheme for http is
          <code>http</code> of course, as the default for secured http is
          <code>https</code> but we show setting the scheme to show it can be
          done. The port for secured communication is also set here.
          On this HttpConfiguration object we add a SecureRequestCustomizer
          which is how a new connector is able to resolve the https connection
          before handing control over to the Jetty Server.
        */
        HttpConfiguration https_config = new HttpConfiguration();
        https_config.setSecureScheme("https");
        https_config.setSecurePort(port);
        https_config.setOutputBufferSize(32768);

        SecureRequestCustomizer src = new SecureRequestCustomizer();
        src.setStsMaxAge(2000);
        src.setStsIncludeSubDomains(true);
        https_config.addCustomizer(src);

        /*
          HTTPS connector
          We create a second ServerConnector, passing in the http configuration
          we just made along with the previously created ssl context factory.
          Next we set the port and a longer idle timeout.
        */
        ServerConnector https = new ServerConnector(server,
                                                    new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
                                                    new HttpConnectionFactory(https_config));
        https.setPort(port);
        https.setIdleTimeout(500000);

        // Add HTTPS connector to server
        server.addConnector(https);

No comments: