Secure SpringBoot: Configuring HTTPS and Enabling HTTP/2
This guide explains why plain HTTP is unsafe for enterprise projects, outlines the core principles and benefits of HTTPS and HTTP/2, compares certificate types, provides step‑by‑step commands to generate self‑signed and authority‑issued certificates, and shows how to configure SpringBoot, enable automatic HTTP‑to‑HTTPS redirects, verify HTTP/2 activation, and apply production‑grade security hardening.
1. HTTP Security Risks
Plain HTTP transmits data in clear text, exposing three core security issues that violate compliance requirements such as China’s GB/T 22239‑2019 and GDPR: eavesdropping, data tampering, and request hijacking.
2. HTTPS Fundamentals
HTTPS is HTTP layered with TLS/SSL, providing encryption, identity authentication, and anti‑tampering. The encryption flow consists of six steps:
Client requests the server’s SSL certificate.
Server returns its certificate (containing the public key and identity information).
Client validates the certificate (expiration, integrity, trusted issuer).
Client generates a random symmetric key, encrypts it with the server’s public key, and sends it to the server.
Server decrypts the symmetric key with its private key.
Both sides use the symmetric key for subsequent communication, ensuring confidentiality.
Current standards are TLS 1.2/TLS 1.3; SSL 3.0 is deprecated.
3. HTTP/2 Advantages
Multiplexing: multiple requests share a single TCP connection, eliminating head‑of‑line blocking.
Header compression (HPACK) reduces request size.
Binary framing speeds parsing.
Server push can proactively send resources.
Priority settings ensure critical APIs (e.g., payment, login) are served first.
Real‑world tests show HTTP/2 improves interface response speed by 30‑50% compared with HTTP/1.1, especially under high concurrency.
4. SSL Certificate Types
Self‑signed certificate
Applicable scenario: local development, testing.
Advantages: free, quick generation, no review.
Disadvantages: not trusted by browsers, shows “not secure” warnings.
Free authority‑issued certificate (e.g., Let’s Encrypt, Alibaba Cloud free SSL)
Applicable scenario: personal projects, small enterprises, testing.
Advantages: free, trusted by browsers, multi‑domain support.
Disadvantages: short validity (usually 1 year), limited features.
Paid authority‑issued certificate
Applicable scenario: production, enterprise, multi‑domain.
Advantages: long validity, multi‑domain, higher security, support.
Disadvantages: requires payment and strict verification.
5. Generating a Self‑Signed Certificate
keytool -genkey -alias tomcat -keyalg RSA -keysize 2048 -validity 3650 -keystore server.jksParameters: -genkey: generate a key pair. -alias tomcat: certificate alias (used later in configuration). -keyalg RSA: encryption algorithm. -keysize 2048: key length (2048 bits or higher). -validity 3650: validity period in days (10 years, sufficient for testing). -keystore server.jks: output file in JKS format.
After execution, copy server.jks into the SpringBoot project’s src/main/resources directory.
6. Obtaining a Production Certificate
Log in to the cloud console (e.g., Alibaba Cloud) and navigate to “SSL Certificate”.
Select “Free Certificate” (Let’s Encrypt or Alibaba Cloud free SSL) and apply.
Enter the domain name (e.g., www.example.com) and verify ownership, preferably via DNS.
After verification (1‑10 minutes), download the certificate in JKS format and rename it to server.jks.
Place the file in the project’s resources directory.
7. SpringBoot Configuration for HTTPS + HTTP/2
7.1 Maven Dependency (pom.xml)
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
</parent>
<groupId>com.example</groupId>
<artifactId>springboot-https-http2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>7.2 application.yml
server:
port: 443 # HTTPS default port
http2:
enabled: true # Enable HTTP/2 (requires HTTPS)
ssl:
enabled: true
key-store: classpath:server.jks
key-store-type: JKS
key-store-password: 123456 # Self‑signed password; replace with production password
key-alias: tomcat
key-password: 123456
ciphers: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
enabled-protocols: TLSv1.2,TLSv1.3
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,application/json,application/javascript
min-response-size: 1024
tomcat:
server-header: "" # Hide Tomcat version7.3 Automatic HTTP‑to‑HTTPS Redirect
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.apache.catalina.connector.Connector;
@Configuration
public class HttpToHttpsConfig {
/** Configure HTTP 80 port to redirect to HTTPS 443 */
@Bean
public ServletWebServerFactory servletWebServerFactory() {
TomcatServletWebServerFactory tomcatFactory = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(org.apache.catalina.Context context) {
// Disable Tomcat HTTP cache (optional security hardening)
org.apache.catalina.webresources.StandardRoot root = new org.apache.catalina.webresources.StandardRoot(context);
root.setCacheMaxSize(0);
context.setResources(root);
}
};
Connector httpConnector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
httpConnector.setScheme("http");
httpConnector.setPort(80);
httpConnector.setSecure(false);
httpConnector.setRedirectPort(443);
tomcatFactory.addAdditionalTomcatConnectors(httpConnector);
return tomcatFactory;
}
}7.4 Testing the Configuration
Start the SpringBoot application; no errors indicate successful configuration.
Open a browser and visit https://localhost (port 443 is implicit).
With a self‑signed certificate the browser shows a “not private” warning; proceed to test.
A trusted authority certificate displays a lock icon, confirming HTTPS works.
8. Verifying HTTP/2 Activation
Method 1 – Chrome DevTools
Open https://localhost and launch DevTools (F12).
Switch to the “Network” tab and refresh.
Check the “Protocol” column; “h2” means HTTP/2 is active.
Method 2 – Command Line
curl -I https://localhostIf the response starts with HTTP/2 200, HTTP/2 is enabled.
Method 3 – Online Tool
Visit https://http2.pro/, input the domain, and the tool reports HTTP/2 status, certificate validity, and cipher suites.
9. Common Reasons HTTP/2 May Not Work
HTTPS not enabled – HTTP/2 requires TLS.
SpringBoot version below 2.4 – upgrade to 2.7.x or later.
JDK version below 8u261 – upgrade to a supported JDK.
Browser does not support HTTP/2 (e.g., Internet Explorer).
10. HTTP/2 Performance Optimizations
Enable server push in Tomcat to pre‑send static assets.
Leverage HPACK header compression (enabled by default).
Merge static resources (CSS/JS) to reduce request count.
Enable Gzip compression in SpringBoot to shrink payloads.
server:
compression:
enabled: true
mime-types: text/html,text/xml,text/plain,application/json,application/javascript
min-response-size: 102411. Production‑Grade Hardening
11.1 Port and Certificate Practices
Use standard ports: 443 for HTTPS, 80 for HTTP.
Never use self‑signed certificates in production; choose a trusted CA.
Store certificates outside the application JAR (e.g., /usr/local/ssl) with restricted permissions.
For multi‑domain projects, obtain a multi‑domain (SAN) certificate.
11.2 Security Enhancements
Enable HSTS to force browsers to use HTTPS:
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Configuration
public class WebSecurityConfig implements WebMvcConfigurer {
@Bean
public Filter hstsFilter() {
return new Filter() {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
chain.doFilter(request, response);
}
};
}
}Configure strong cipher suites and disable weak protocols (TLS 1.0/1.1, SSL 3.0):
server:
ssl:
ciphers: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
enabled-protocols: TLSv1.2,TLSv1.3Hide Tomcat version information:
server:
tomcat:
server-header: ""11.3 Certificate Renewal and Backup
Free certificates expire after one year; renew 15‑30 days before expiration.
Backup the certificate file and its password securely.
After renewal, replace the old file and restart the application.
11.4 Deploying Behind Nginx
Typical production architecture places HTTPS and HTTP/2 termination at Nginx, while SpringBoot runs on HTTP port 8080.
server {
listen 80;
server_name www.example.com;
return 301 https://$host$request_uri; # HTTP → HTTPS redirect
}
server {
listen 443 ssl http2;
server_name www.example.com;
ssl_certificate /usr/local/ssl/server.pem;
ssl_certificate_key /usr/local/ssl/server.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
location / {
proxy_pass http://localhost:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}Centralizing TLS termination in Nginx simplifies certificate management, enables load balancing, and maximizes HTTP/2 performance.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Workshop
Focused on Java backend technologies, sharing fundamentals, multithreading, JVM, the Spring ecosystem, microservices, distributed systems, high concurrency, source‑code analysis, and practical experience. Continuously delivers high‑quality original content, interview guides, and learning roadmaps to help Java developers progress from beginner to advanced, enhancing technical skills and core competitiveness.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
