https://www.thomasvitale.com/https-spring-boot-ssl-certificate/
Step 1: get SSL Certificate
Method 1: generate self-signed certificate via keytool
.
// PK12 formate
keytool -genkeypair -alias {your alias} -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore {your keyname}.p12 -validity 3650
Before getting started, we’ll create a self-signed certificate. We’ll use either of the following certificate formats:
- PKCS12: Public Key Cryptographic Standards is a password protected format that can contain multiple certificates and keys; it’s an industry-wide used format
- JKS: Java KeyStore is similar to PKCS12; it’s a proprietary format and is limited to the Java environment.
We can use either of keytool or OpenSSL tools to generate the certificates from the command line. Keytool is shipped with Java Runtime Environment and OpenSSL could be downloaded from here.
Step 2: config Spring Boot
# Server
# SSL
# ssl port
server.port=8143
# use Spring Security
server.ssl.enabled=true
# The format used for the keystore. It could be set to JKS in case it is a JKS file
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keystore/pteback.p12
# The password used to generate the certificate
server.ssl.key-store-password=pteback
# The alias mapped to the certificate
server.ssl.key-alias=pteback
PTEApplication.java
/**
* For SSL
* @return
*/
@Bean
public ServletWebServerFactory servletContainer() {
// Enable SSL Traffic
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
SecurityConstraint securityConstraint = new SecurityConstraint();
securityConstraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
securityConstraint.addCollection(collection);
context.addConstraint(securityConstraint);
}
};
// Add HTTP to HTTPS redirect
tomcat.addAdditionalTomcatConnectors(httpToHttpsRedirectConnector());
return tomcat;
}
/*
We need to redirect from HTTP to HTTPS. Without SSL, this application used
server port. With SSL it will use port 8443. So, any request for 8082 needs to be
redirected to HTTPS on 8443.
*/
@Value("${server.port}")
private Integer desPort;
private Connector httpToHttpsRedirectConnector() {
Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
connector.setScheme("http");
connector.setPort(8081);
connector.setSecure(false);
connector.setRedirectPort(desPort);
return connector;
}