Cesar Justo
Cesar Justo

Reputation: 803

How to redirect http traffic to https with spring boot 2.3.1

Good afternoon, I am working with spring boot and already implement http safe mode (https), but I need to know how to redirect http requests to https, and if it is necessary to specify a particular safe port like 443, or I can do it with any port. At the moment I use ports 8080 8443

My class

Main Class

package com.prueba.https;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

@SpringBootApplication
public class PruebaHttpsApplication {

    public static void main(String[] args) {
        SpringApplication.run(PruebaHttpsApplication.class, args);
    }

}

Request Class

package com.prueba.http.request;

public class PruebaRequest {

    public String nombre;

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

}

Response Class

package com.prueba.https.response;

public class PruebaResponse {

    public String saludo;

    public String getSaludo() {
        return saludo;
    }

    public void setSaludo(String saludo) {
        this.saludo = saludo;
    }


}

Controller Class

package com.prueba.https.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.prueba.http.request.PruebaRequest;
import com.prueba.https.response.PruebaResponse;

@RestController
public class PruebaController {


    @PostMapping(value = "/PruebaHTTPS") 
    public Object PruebaController(@RequestBody PruebaRequest req) {
        PruebaResponse res = new PruebaResponse();
        res.setSaludo("Hola " +req.getNombre());
        return res;

    }

}

application properties

server.port=8443

server.ssl.key-store = classpath:keystore.p12
server.ssl.key-store-password = pass
server.ssl.keyStoreType = PKCS12
server.ssl.keyAlias = tomcat

pom xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.prueba.https</groupId>
    <artifactId>PruebaHTTPS</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>PruebaHTTPS</name>
    <description>Pruebas HTTPS</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Structure of my project

enter image description here

Conexion HTTPS

enter image description here

Conexion HTTP

enter image description here

UPDATE

Use the following code that works for my version of spring, however it gives me error with http requests:

package com.prueba.https;
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan
@Configuration
@EnableAutoConfiguration
public class WebsocketSourceConfiguration {

      @Bean
      public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new  TomcatServletWebServerFactory() {
          @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(getHttpConnector());
        return tomcat;
      }

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



}

HTTPS (8443)

enter image description here

HTTP(8443)

enter image description here

HTTP(8080)

enter image description here

Why can't I point to http: 8443 and redirect me to https?

Upvotes: 1

Views: 2594

Answers (1)

Nitesh Sharma
Nitesh Sharma

Reputation: 555

To redirect your HTTP request to HTTPS requests you need add below configurations :

@Bean
public 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(redirectConnector());
  return tomcat;
}

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

I hope this will work for you.

Upvotes: 1

Related Questions