Embedded Jetty with client certificates
Every time I start with an embedded Jetty server, I can’t find any up to date documentation and have to mess around with old, obsolete and deprecated documentation to get things working.
Today was no different… I wanted to create a simple embedded HTTPS server that required the clients to present a certificate. Most documentation I could find was relevant for older versions and either wasn’t working, or presented me with a whole load of deprecation warnings. However, after some messing around, I managed to get this working, and, as with most things, it wasn’t really that hard and using the javadocs, actually very straightforward.
So for those of you using Jetty 8 and wanting to use client-side ssl, you can use the following java class to start a HTTPS server, which in this example contains a single servlet.
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ssl.SslSocketConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.ssl.SslContextFactory;
public class IdentityForwardingProxy {
// the keystore (with one key) we'll use to make the connection with the
// broker
private final static String KEYSTORE_LOCATION = "src/main/resources/client_keystore.jks";
private final static String KEYSTORE_PASS = "secret";
// the truststore we use for our server. This keystore should contain all the keys
// that are allowed to make a connection to the server
private final static String TRUSTSTORE_LOCATION = "src/main/resources/truststore.jks";
private final static String TRUSTSTORE_PASS = "secret";
/**
* Simple starter for a jetty HTTPS server.
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// create a jetty server and setup the SSL context
Server server = new Server();
SslContextFactory sslContextFactory = new SslContextFactory(KEYSTORE_LOCATION);
sslContextFactory.setKeyStorePassword(KEYSTORE_PASS);
sslContextFactory.setTrustStore(TRUSTSTORE_LOCATION);
sslContextFactory.setTrustStorePassword(TRUSTSTORE_PASS);
sslContextFactory.setNeedClientAuth(true);
// create a https connector
SslSocketConnector connector = new SslSocketConnector(sslContextFactory);
connector.setPort(8443);
// register the connector
server.setConnectors(new Connector[] { connector });
ServletContextHandler scHandler = new ServletContextHandler(server,"/");
scHandler.addServlet(NameOfServlet.class, "/");
server.start();
server.join();
}
}