Building a secured Java web server using Spark framework and Nginx

0

Spark framework (www.sparkjava.com) is a small Java framework used to build a REST server quickly. You can build a Java web server with only a few lines of code. But adding SSL to your server needs more effort.

Java used its own format for the keystore file which contains keys. First of all, you need to generate your private key. Java key tool will store it in a keystore file .jks. The following command creates a key has 2048 bit length for localhost valid in one year:
keytool -genkey -alias localhost -keyalg RSA -keystore KeyStore.jks -validity 365 -keysize 2048

Now you have your private key in the keystore file. Here is a code snippet to build a web server using Spark framework:

import spark.Request;
import spark.Response;

import static spark.Spark.*;

public class Server {
private final int port = 12345;

public Server() {
port(port);
secure(“KeyStore.jks”, “password”, null, null);

get(“/”, (request, response) -> {
return “Hello World”;
});
}
}

This code load the keystore you’ve recently created to support SSL. Try to access your server with the URL: https://localhost:12345/, you’ll get the text “Hello World”.

Your web server supports SSL, but it’s quite dangerous when you exposing it directly to the world. Enhancing security of your web server by adding a proxy in front of it. Requests will go to your proxy first, then your proxy forward it to your server.

I use Nginx (www.nginx.com) for this purpose. This is a famous web server that solved the C10K problem (https://en.wikipedia.org/wiki/C10k_problem). After installing it, change its configuration file (conf/nginx.conf) to allow forwarding requests to your server:

# HTTPS server
#
server {
listen 443 ssl;
server_name localhost;

ssl_certificate “localhost.crt”;
ssl_certificate_key “localhost.key”;

server_tokens off;

#ssl_session_cache shared:SSL:1m;
#ssl_session_timeout 5m;

#ssl_ciphers HIGH:!aNULL:!MD5;
#ssl_prefer_server_ciphers on;

location / {
proxy_pass https://localhost:12345;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}

Please replace ‘localhost’ at ‘server_name’ field by your real domain. This configuration file guides Nginx server to listen at port 443 (SSL port) and forward requests to your web server at port 12345. Please note that you’ll need a private key and a certificate for your Nginx server. They’re different from the keystore of your web server. The OpenSSL tool (www.openssl.org) will help you to generate them easily, or you may want to contact to a CA to get an authorized certificate.

Try to open the URL https://. It’ll return ‘Hello World’. You’ve built a secured java web server successfully!

Share.

About Author