Generate a Self‑Signed HTTPS Certificate and Enable HTTPS in Spring Boot

This guide explains how to use JDK's keytool to create a self‑signed HTTPS certificate, configure Spring Boot to serve over HTTPS, set up HTTP‑to‑HTTPS redirection, and verify the setup with sample controller code and runtime logs.

Senior Brother's Insights
Senior Brother's Insights
Senior Brother's Insights
Generate a Self‑Signed HTTPS Certificate and Enable HTTPS in Spring Boot

Background

HTTPS is increasingly required for website security and SEO, but purchasing a certificate can be costly for individual developers. Free certificates can be obtained from domain registrars or specialized providers. This article demonstrates how to generate a self‑signed certificate with the JDK keytool utility and integrate it into a Spring Boot application.

Certificate Generation

The JDK includes keytool for managing keystores. After ensuring the JAVA_HOME environment variable is set, run the following command to create a PKCS#12 keystore named https.p12 that is valid for 365 days:

keytool -genkey -alias springboot-https -keyalg RSA -keysize 2048 -keystore ./https.p12 -validity 365

Parameter meanings:

genkey : generate a new key pair.

alias : name of the entry in the keystore.

keyalg : algorithm, here RSA.

keysize : key length (2048 bits).

keystore : output file location.

validity : validity period in days.

During execution you will be prompted for the keystore password and certificate details (name, organization, location, country, etc.). Confirm the distinguished name (DN) when asked. After the command finishes, a file https.p12 appears in the current directory.

Spring Boot Integration

Copy the generated https.p12 file into the src/main/resources directory of the Spring Boot project (the author placed it there directly during generation).

Configure the certificate in application.properties:

# Set HTTPS port
server.port=8443
# Keystore file name
server.ssl.key-store=https.p12
# Keystore alias
server.ssl.key-alias=springboot-https
# Keystore password (the one set during generation)
server.ssl.key-store-password=123456

These properties are defined in org.springframework.boot.web.server.Ssl and can be extended by inspecting that class.

Simple Controller Test

Create a basic controller to verify HTTPS works:

@RestController
public class HttpsController {
    @RequestMapping("/")
    public String hello(){
        return "Hello Spring-Boot-Https!";
    }
}

Run the application; the console logs show Tomcat starting on port 8443 (HTTPS):

INFO  --- Tomcat initialized with port(s): 8443 (https)
INFO  --- Tomcat started on port(s): 8443 (https) with context path ''

Access https://localhost:8443 in a browser. Because the certificate is self‑signed, the browser displays a security warning; proceed by clicking “Advanced” → “Proceed to localhost”. The page returns the string from the controller.

HTTP‑to‑HTTPS Redirection

To ensure users who type http://localhost:8080 are automatically redirected to HTTPS, add a custom Tomcat configuration bean:

@Configuration
public class HttpsConfig {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory(){
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context){
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        factory.addAdditionalTomcatConnectors(httpsConnector());
        return factory;
    }

    private Connector httpsConnector(){
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8443);
        return connector;
    }
}

This bean creates an additional HTTP connector on port 8080 that redirects all requests to the HTTPS port 8443. After restarting, the logs show both ports listening, and navigating to http://localhost:8080 results in an automatic redirect to https://localhost:8443.

Additional Notes

You can add multiple SecurityConstraint entries to handle different URL patterns, e.g., exclude static resources from redirection by setting userConstraint="NONE" for /static/*.

When copying the example code, rename variables to avoid naming conflicts.

With these steps, the Spring Boot application now serves traffic securely over HTTPS and gracefully redirects HTTP requests.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootTLSHTTPSself-signed certificatekeytool
Senior Brother's Insights
Written by

Senior Brother's Insights

A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.