Sometimes you may want to test HTTPS support for embedded Jetty, a self-signed certificate is enough for testing. This post shows how to enable HTTP support with self-signed certificate for embedded Jetty 9.

Generate the keystore

The first step is to generate a keystore using keytool. -validity 3650 means the certificate is valid for 3650 days.

$ keytool -keystore mykey.jks -alias mykey -keyalg RSA -keysize 2048 -sigalg SHA256withRSA -genkey -validity 3650

Configure Jetty

We can choose to support both HTTP and HTTPS by adding two ServerConnectors in Jetty. In the code below, we create a Server and add a ServerConnector for HTTP on port httpPort.

final Server server = new Server();
final HttpConfiguration httpConfiguration = new HttpConfiguration();

final ServerConnector http = new ServerConnector(server,
    new HttpConnectionFactory(httpConfiguration));

Then we create a SslContextFactory which loads the keystore file in path keyStorePath. A new ServerConnector is created for HTTPS on port httpsPort.

final SslContextFactory sslContextFactory = new SslContextFactory(keyStorePath);
final HttpConfiguration httpsConfiguration = new HttpConfiguration(httpConfiguration);
httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
final ServerConnector httpsConnector = new ServerConnector(server,
    new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
    new HttpConnectionFactory(httpsConfiguration));

Obfuscated password

The keystore's password can be obfuscated using The command below shows how to obfuscate the password password. The output should be used as the password. The obfuscated passwords start with OBF:.

$ java -cp jetty-util-9.2.17.v20160517.jar password

HTTPS only

If you only want to enable HTTPS, you can either remove the ServerConnector for HTTP or use org.eclipse.jetty.server.handler.SecuredRedirectHandler to redirect HTTP to HTTPS. SecuredRedirectHandler should be put before other handlers in the handlers chain.