Как перенаправить http-трафик c на https с помощью Spring Boot 2.3.1 - PullRequest
0 голосов
/ 18 июня 2020

Добрый день, я работаю с весенней загрузкой и уже реализую безопасный режим http (https), но мне нужно знать, как перенаправить HTTP-запросы на https, и если необходимо указать конкретный безопасный порт, например 443, или Я могу это сделать с любым портом. На данный момент я использую порты 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;
    }


}

Класс контроллера

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;

    }

}

свойства приложения

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>

Структура моего проекта

enter image description here

Conexion HTTPS

enter image description here

Conexion HTTP

enter image description here

ОБНОВЛЕНИЕ

Используйте следующий код, который работает для моей версии Spring, однако он дает мне ошибку с HTTP-запросами:

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

Почему я не могу указать на http: 8443 и перенаправить меня на https?

1 Ответ

0 голосов
/ 18 июня 2020

Чтобы перенаправить ваш HTTP запрос на HTTPS, вам необходимо добавить следующие конфигурации:

@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;
}

Надеюсь, это сработает для вас.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...