HTTPS Setup for Spring Boot

This is a short step-by-step recipe for setup of secure HTTPS connections for Spring Boot server applications (REST API). This recipe is used in courses IDATA2301 Web technologies and IDATA2306 Application Development at NTNU, campus Aalesund.

This recipe is based on the guide "Spring Boot Secured By Let's Encrypt".

Here we assume that you have a .pem file containing the TLS certificate with your private key. See recipe on HTTPS for Nginx on how to generate it.

Instructions:

  1. Open the terminal as a root. If you have logged in as a non-root user, become root by using command sudo su
  2. Convert the Certbot-generated key to PKCS12 format. Certbot saved your key in directory /etc/letsencrypt/live/yourdomain. For example, if your domain is example.com, the key is saved in directory /etc/letsencrypt/live/example.com. Go to that directory: cd /etc/letsencrypt/live/example.com. Then Convert the key:
    openssl pkcs12 -export -in fullchain.pem -inkey privkey.pem -out keystore.p12 -name tomcat -CAfile chain.pem -caname root
    You can protect the key with a password, but using no password is OK as well. If everything went well, now you have a file /etc/letsencrypt/live/example.com/keystore.p12
  3. Copy the keystore.p12 to project files: src/main/resources - the same directory where the application.properties is
  4. Change the permissions for the file so that the non-root user can read it: sudo chmod a+r src/main/resources/keystore.p12 Note: this will make the key file (including the private key) readable for ALL users on your server. If this is not what you need, you can make it readable only to your user. For example, if the username of your user is `dev`, then you can make `dev` the owner of the key with this command: sudo chown dev:root src/main/resources/keystore.p12 The important thing is that the key file is readable for the user which will run the Spring Boot application.
  5. Configure your Spring Boot app to use HTTPS, and only HTTPS. Add the following lines to your application.properties (Remember to replace example.com with your domain!):
    server.port=8443
    server.ssl.key-store=classpath:keystore.p12
    server.ssl.key-store-password=your-password (if you don't use password for the key, still need this line, just without a value)
    server.ssl.keyStoreType=PKCS12
    server.ssl.keyAlias=tomcat
  6. Package the application in a fat JAR with the command mvn package
  7. You can run the application by running java -jar target/*.jar

That's all, Folks!