Thursday, April 2, 2009

Securing Grizzly Web Server

Running GrizzlyWebServer is very easy and lightweight. Serving HTTPS? The same.

It's just one more step to perform, provide Grizzly with SSL configuration.

But first thing first. Lets create GrizzlyWebServer telling it to serve secure content.
Just invoke this constructor:

/**
* Create a WebServer that listen for secure tls/https requests
* @param port The port opened
* @param webResourcesPath the path to the web resource (ex: /var/www)
* @param secure true if https needs to be used.
*/
public GrizzlyWebServer(int port, String webResourcesPath, boolean secure)
Say like this:
gws = new GrizzlyWebServer(PORT, ".", true);
If you would try start() now you get exception.
What is missing is SSL configuration.

Grizzly comes with SSLConfig helper class, that allows you to work with SSL configuration easily.
SSLConfig cfg = new SSLConfig();
This constructor fetches configuration from default properties locations, which are:
  • trust store - javax.net.ssl.trustStore
  • key store - javax.net.ssl.keyStore
  • trust store password - javax.net.ssl.trustStorePassword
  • key store password - javax.net.ssl.keyStorePassword
  • trust store type - javax.net.ssl.trustStoreType
  • key store type - javax.net.ssl.keyStoreType
If you need to override any configuration value, like key store location, just do:

URL resource = getClass().getClassLoader().getResource("test-keystore.jks");
if (resource != null) {
cfg.setKeyStoreFile(new File(resource.toURI()).getAbsolutePath());
} else {
// Couldn't find keystore, exit appropriately.
}
Once you have configuration ready give it to Grizzly:
gws.setSSLConfig(cfg);
And you are done, now do normal setup like providing GrizzlyAdapters and start().

Default configuration values are:
  • key store file - keystore.jks
  • key store type - JKS
  • key store algorithm - SunX509
  • key store pass - changeit
  • trust store file - truststore.jks
  • trust store type - JKS
  • trust store algorithm - SunX509
  • trust store pass - changeit
In case you want to authenticate your clients with certificates signed by your trusted CA you have to include CA public certificate in trust store.
Trust store configuration is as simple as key store configuration, methods just start with trust not key.

And that's how easy encryption with Grizzly is :-)