How to redirecting HTTP to HTTPS in Java+How to redirecting HTTP to HTTPS+redirecting HTTP to HTTPS in Spring

Report
Question

Please briefly explain why you feel this question should be reported .

Report
Cancel

To redirect – Requests using HTTP (non-secure) for URLs whose transport guarantee is CONFIDENTIAL are automatically redirected to the same URL using HTTPS.

Add the following configuration to your web.xml
<security-constraint>
<web-resource-collection>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

Spring

Spring boot SSL Configuration


First we need to configure the copy the generated keystore file (ssl-server.jks) into the resources folder and then open the application.properties and add the below entries.

Configuration with HTTPS

server.port=8443
server.ssl.key-alias=selfsigned_localhost_sslserver
server.ssl.key-password=changeit
server.ssl.key-store=classpath:ssl-server.jks
server.ssl.key-store-provider=SUN
server.ssl.key-store-type=JKS

Redirect HTTP requests to HTTPS

This is an optional step in case you want to redirect your HTTP traffic to HTTPS, so that the full site becomes secured. To do that in spring boot, we need to add HTTP connector at 8080 port and then we need to set redirect port 8443. So that any request in 8080 through http, it would be automatically redirected to 8443 and https.

To do that you just need to add below configuration.

@Bean
public EmbeddedServletContainerFactory servletContainer() {
  TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
//Set the value
      @Override
      protected void postProcessContext(Context context) {
        SecurityConstraint securityConstraint = new SecurityConstraint();
        securityConstraint.setUserConstraint("CONFIDENTIAL");
        SecurityCollection collection = new SecurityCollection();
//set the wildcart
        collection.addPattern("/*");
        securityConstraint.addCollection(collection);
        context.addConstraint(securityConstraint);
      }
    };
  
  tomcat.addAdditionalTomcatConnectors(redirectHttpToHttpsConnector());
  return tomcat;
}

private Connector redirectHttpToHttpsConnector() {
  Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//redirect settings
  connector.setScheme("http");
  connector.setPort(8080);

  connector.setSecure(false);
  connector.setRedirectPort(8443);
  
  return connector;
}

Build the code with maven

mvn clean install

start the application.

Run and test http://localhost:8080/secured.

** It would be automatically redirected to HTTPS secured URL.

0
msmanimaran@gmail.com 2 years 2021-08-29T12:31:54+02:00 0 Answers 23 views 0

Leave an answer

Captcha Click on image to update the captcha .