Enabling HTTPS in Spring Boot application

Enabling HTTPS in Spring Boot application

Encrypting network communication using SSL is currently a standard. Therefore, the need for HTTPS configuration in web applications often arises. In today’s post I will present how easy it is to set up a secure HTTPS channel in SpringBoot application.

1. Sample application

To present the SSL configuration in the SpringBoot application I will use the HelloWorld example like below. After starting and entering http://localhost: 8080/ you can see that the site is not secure (says the http protocol itself). After changing the protocol to https, the page does not open.

package com.bettercoding.lab;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class WebApp {
    public static void main(String[] args) {
        SpringApplication.run(WebApp.class, args);
    }

    @RestController
    public static class HelloController {

        @RequestMapping("/")
        public String index() {
            return "Greetings from Spring Boot!";
        }
    }
}

2. SSL configuration in the SpringBoot application

The entire SSL configuration in the SpringBoot application comes down to preparing or generating a JKS keystore with a key and certificate, and then configuring the application to encrypt network traffic using it.

2.1 Generating keystore with pair: key, certificate

To generate a certificate, you can use the keytool tool available in JDK. The following command allows you to generate a key/certificate pair, and save them in the keystore named tmp_keystore.jks.

keytool -genkey -keyalg RSA -alias selfsigned -keystore tmp_keystore.jks -storepass password -validity 360 -keysize 2048

2.2 Configuring the SpringBoot application

The last step is to configure the appropriate settings in the application. To do this, add the following properties into application.properties file. Of course, the application.properties file is just one of the configuration methods. You can find more about this on https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

server.port=443
server.ssl.key-alias=selfsigned
server.ssl.key-password=password
server.ssl.key-store=src/main/resources/tmp_keystore.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-password=password
server.ssl.key-store-type=JKS

Then, after starting the application and entering https://localhost:443, you can check that the site is properly secured by means of SSL.

If you think this post is valuable, please leave me +1 or just share it.
Your action helps me to reach a wider audience.
Thank You in advance.

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu