Spring Boot makes it easy to enable HTTPS in your application. You can enable HTTPS by using a self-signed certificate or a certificate issued by a trusted certificate authority.
Here is an example of how you can enable HTTPS in a Spring Boot application:
- Create a self-signed certificate:
1 2 |
keytool -genkeypair -alias myapp -keyalg RSA -keystore keystore.jks -storepass password -validity 365 -keysize 2048 |
- Add the following properties to your
application.properties
orapplication.yml
file:
1 2 3 4 5 |
server.port: 8443 server.ssl.key-store: classpath:keystore.jks server.ssl.key-store-password: password server.ssl.key-alias: myapp |
- Add the following code to your main class to configure HTTPS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
@Value("${server.ssl.key-store}") private String keyStore; @Value("${server.ssl.key-store-password}") private String keyStorePassword; @Value("${server.ssl.key-alias}") private String keyAlias; @Bean public ServletWebServerFactory servletContainer() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); tomcat.addAdditionalTomcatConnectors(createSslConnector()); return tomcat; } private Connector createSslConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler(); try { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(this.keyStore), this.keyStorePassword.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, this.keyStorePassword.toCharArray()); connector.setScheme("https"); connector.setSecure(true); connector.setPort(8443); protocol.setSSLEnabled(true); protocol.setKeyAlias(this.keyAlias); protocol.setKeystoreType("JKS"); protocol.setKeystorePass(this.keyStorePassword); protocol.setKeystoreFile(this.keyStore); protocol.setSslProtocol("TLS"); protocol.setKeyManagerFactoryAlgorithm(KeyManagerFactory.getDefaultAlgorithm()); protocol.setKeyManagerFactory(keyManagerFactory); } catch (Exception ex) { throw new IllegalStateException("can't access keystore: [" + "keystore" + "] or truststore: [" + "keystore" + "]", ex); } return connector; } |
That’s it! You can now run your Spring Boot application and access it using https://localhost:8443
.
Note: The example above uses a self-signed certificate for demonstration purposes only.
In a production environment, it is recommended to use a certificate from a trusted certificate authority to secure your application.