How to enable HTTPS in Spring Boot Restful service

How to enable HTTPS in Spring Boot Restful service

Spring version 4.3.11

Three things to do


  1. Get yourself a SSL certificate: 
  2. Enable HTTPS in Spring Boot
  3. Redirect HTTP to HTTPS 

To generate SSL certificate
Go to your workspace folder and type in the following command

 keytool -genkey -alias tomcat
 -storetype PKCS12 -keyalg RSA -keysize 2048
 -keystore keystore.p12 -validity 3650




Type in the values that the certificate wants. Once competed it will generate a file called "keystore.p12" in the folder

Enable HTTPS in Spring Boot

Go to application.properties file under src/main/resources of your Spring Boot application:

server.port: 8443
server.ssl.key-store: keystore.p12
server.ssl.key-store-password: mypassword
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat

Redirect HTTP to HTTPS

Add the folowing code in ur Spring Application class

@Beanpublic EmbeddedServletContainerFactory servletContainer() {
   TomcatEmbeddedServletContainerFactory tomcat = 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);      
        }
   };   tomcat.addAdditionalTomcatConnectors(initiateHttpConnector());   
        return tomcat;
}

private Connector initiateHttpConnector() {
   Connector connector = new Connector
           ("org.apache.coyote.http11.Http11NioProtocol");   
   connector.setScheme("http");   
   connector.setPort(8080);   
   connector.setSecure(false);   
   connector.setRedirectPort(8443);
   return connector;
}

I refered this link https://drissamri.be/blog/java/enable-https-in-spring-boot/


No comments:

 Python Basics How to check the version of Python interpreter mac terminal

Popular in last 30 days