Goal

This article describes how to enable HTTPS for spring boot rest service.

Used technologies

This Example is based on the previous spring boot example and it enables https

1. 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;
	}

2. 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

3. 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

4. Run the Main Application

mvn clean package

5. 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)