By Marone: September 2016
Secure Spring boot using HTTPS
Goal
This article describes how to enable HTTPS for spring boot rest service. This Example is based on the previous spring boot example and it enables httpsUsed technologies
JDK 1.8Maven 3.2
Extend the Main class
private Connector createHttpConnector() {
Connector httpConnector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
httpConnector.setScheme("http");
httpConnector.setPort(8080);
httpConnector.setRedirectPort(8443);
return httpConnector;
}
@Bean
public EmbeddedServletContainerFactory createAdditionalTomcatConnector() {
TomcatEmbeddedServletContainerFactory embeddedTomcat = new TomcatEmbeddedServletContainerFactory() {
@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);
}
};
embeddedTomcat.addAdditionalTomcatConnectors(createHttpConnector());
return embeddedTomcat;
}
Generate a self-signed certifcate
Run the following command in src/main/resources/ssl/
keytool -genkey -keyalg RSA -alias bootalias -storetype PKCS12 -keysize 2048 -keystore springboot_ks.p12 -validity 720
Now enter the recommended details (first and last name, organization, ..etc)
Confirm with yes
Provide a application yml file
server:
port: 8443
http.port: 8080
ssl:
key-store: src/main/resources/ssl/springboot_ks.p12
key-store-password: password99
keyStoreType: PKCS12
keyAlias: bootalias
Run the Main Application
mvn clean package
Call the url
if you type http://localhost:8080 it will be redirected into https://localhost:8443 Warning! Your browser will warn you that the connection is untrusted (in case of Firefox)