복붙노트

[SPRING] HTTPS / HTTP 포트를 실행하기 위해 Spring Boot를 설정하는 방법

SPRING

HTTPS / HTTP 포트를 실행하기 위해 Spring Boot를 설정하는 방법

스프링 부트에는 웹 포트 및 SSL 설정을 구성 할 수있는 몇 가지 속성이 있지만 SSL 인증서가 설정되면 http 포트가 https 포트가됩니다.

그렇다면 두 포트를 어떻게 계속 유지할 수 있습니까? 예를 들어 80과 443을 동시에 사용할 수 있습니까?

보시다시피, 한 포트에 대한 속성 만 있습니다.이 경우 "server.ssl"이 활성화되어 있으면 http 포트가 자동으로 비활성화됩니다.

##############
### Server ###
##############
server.port=9043
server.session-timeout=1800
server.ssl.key-store=file:///C:/Temp/config/localhost.jks
server.ssl.key-store-password=localhost
server.ssl.key-password=localhost
server.ssl.trust-store=file:///C:/Temp/config/localhost.jks
server.ssl.trust-store-password=localhost

Tomcat 또는 Undertow도 사용하려고합니다. 나는 어떤 도움을 주셔서 감사합니다!

해결법

  1. ==============================

    1.속성을 사용하는 스프링 부트 구성은 하나의 커넥터 만 구성 할 수 있습니다. 당신이 필요로하는 것은 여러 개의 커넥터이며 이것을 위해서는 Configuration 클래스를 작성해야합니다. 의 안내에 따라

    속성을 사용하는 스프링 부트 구성은 하나의 커넥터 만 구성 할 수 있습니다. 당신이 필요로하는 것은 여러 개의 커넥터이며 이것을 위해서는 Configuration 클래스를 작성해야합니다. 의 안내에 따라

    https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-developing-web-applications.html#boot-features-customizing-embedded-containers

    아래에서 EmbeddedServletContainerCustomizer를 통해 https를 설정하고 http를 통해 http를 구성하는 작업 예제를 찾을 수 있습니다.

    http://izeye.blogspot.com/2015/01/configure-http-and-https-in-spring-boot.html?showComment=1461632100718#c4988529876932015554

    server:
      port:
        8080
      ssl:
        enabled:
          true
        keyStoreType:
          PKCS12
        key-store:
          /path/to/keystore.p12
        key-store-password:
          password
      http:
        port:
          8079
    
    @Configuration
    public class TomcatConfig {
    
    @Value("${server.http.port}")
    private int httpPort;
    
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                if (container instanceof TomcatEmbeddedServletContainerFactory) {
                    TomcatEmbeddedServletContainerFactory containerFactory =
                            (TomcatEmbeddedServletContainerFactory) container;
    
                    Connector connector = new Connector(TomcatEmbeddedServletContainerFactory.DEFAULT_PROTOCOL);
                    connector.setPort(httpPort);
                    containerFactory.addAdditionalTomcatConnectors(connector);
                }
            }
        };
    }
    }
    
  2. ==============================

    2.현재 받아 들여지는 답변은 완벽하게 작동하지만 스프링 부트 2.0.0 이상에서 작동하게하려면 약간의 적응이 필요합니다 :

    현재 받아 들여지는 답변은 완벽하게 작동하지만 스프링 부트 2.0.0 이상에서 작동하게하려면 약간의 적응이 필요합니다 :

    @Component
    public class HttpServer {
      @Bean
      public ServletWebServerFactory servletContainer(@Value("${server.http.port}") int httpPort) {
          Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
          connector.setPort(httpPort);
    
          TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
          tomcat.addAdditionalTomcatConnectors(connector);
          return tomcat;
      }
    }
    

    또는 kotlin 버전 :

    @Component
    class HttpServer {
      @Bean
      fun servletContainer(@Value("\${server.http.port}") httpPort: Int): ServletWebServerFactory {
        val connector = Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL)
        connector.setPort(httpPort)
    
        val tomcat = TomcatServletWebServerFactory()
        tomcat.addAdditionalTomcatConnectors(connector)
        return tomcat
      }
    }
    
  3. ==============================

    3.Spring Boot는 단지 설정별로 하나의 포트를 열 수 있습니다. 두 번째 포트는 프로그래밍 방식으로 열어야합니다.

    Spring Boot는 단지 설정별로 하나의 포트를 열 수 있습니다. 두 번째 포트는 프로그래밍 방식으로 열어야합니다.

    import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
    import org.springframework.boot.web.server.WebServerFactoryCustomizer;
    
    @Configuration
    public class UndertowConfig {
    
    @Value("${server.http.port}")
    private int httpPort;
    
    @Value("${server.http.interface}")
    private String httpInterface;
    
    @Bean
    public WebServerFactoryCustomizer<UndertowServletWebServerFactory> containerCustomizer() {
        return (WebServerFactoryCustomizer) factory -> {
            UndertowServletWebServerFactory undertowFactory = (UndertowServletWebServerFactory) factory;
            undertowFactory.getBuilderCustomizers().add(builder -> {
                builder.addHttpListener(httpPort, httpInterface);
            });
        };
    }
    

    }

    Spring은 사용 가능한 속성 소스에서 HTTP 또는 HTTPS 포트 읽기 속성 중 하나를 열 수 있습니다. 아래 그림과 같이 적절한 구성을 추가하면 HTTPS 포트를 열어도 충분합니다.

    #default secured port (Spring will open it automatically)
    server.port=8443
    #additional HTTP port (will open it in UndertowConfig)
    server.http.port=8080
    #Open to the world
    server.http.interface=0.0.0.0
    #These settings tell Spring to open SSL port
    server.ssl.keystore=file:${APP_BASE}/conf/server/ssl_selfsigned/server.keystore
    server.ssl.key-store-password=xyz
    server.ssl.key-password=xyz
    

    이렇게하면 HTTP 포트를 연 것과 같은 방법으로 다른 SSL 포트를 열 수 있습니다.

     .addHttpsListener(ssl_port, httpInterface, getSSLContext());
    

    SSL 컨텍스트를 만드는 방법입니다.

    import javax.net.ssl.*;
    import java.io.InputStream;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.security.KeyStore;
    
    public SSLContext getSSLContext() throws Exception
    {
        return createSSLContext(loadKeyStore(serverKeystore,keyStorePassword),
                loadKeyStore(serverTruststore,trustStorePassword));
    
    }
    
    
    private SSLContext createSSLContext(final KeyStore keyStore,
                                        final KeyStore trustStore) throws Exception {
    
        KeyManager[] keyManagers;
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
        keyManagers = keyManagerFactory.getKeyManagers();
    
        TrustManager[] trustManagers;
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        trustManagers = trustManagerFactory.getTrustManagers();
    
        SSLContext sslContext;
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
    
        return sslContext;
    }
    
    
    private static KeyStore loadKeyStore(final String storeLoc, final String storePw) throws Exception {
        InputStream stream = Files.newInputStream(Paths.get(storeLoc));
        if(stream == null) {
            throw new IllegalArgumentException("Could not load keystore");
        }
        try(InputStream is = stream) {
            KeyStore loadedKeystore = KeyStore.getInstance("JKS");
            loadedKeystore.load(is, storePw.toCharArray());
            return loadedKeystore;
        }
    }
    
  4. ==============================

    4.다음을보십시오 : https://github.com/creactiviti/spring-boot-starter-acme. LetsEncrypt 기반 SSL 인증서를 자동으로 생성하기가 매우 쉽습니다.

    다음을보십시오 : https://github.com/creactiviti/spring-boot-starter-acme. LetsEncrypt 기반 SSL 인증서를 자동으로 생성하기가 매우 쉽습니다.

    README에서 :

  5. ==============================

    5.또 다른 스프링 부트 2.x 솔루션 :

    또 다른 스프링 부트 2.x 솔루션 :

    private static final int HTTP_PORT = 80;
    private static final int HTTPS_PORT = 443;
    private static final String HTTP = "http";
    private static final String USER_CONSTRAINT = "CONFIDENTIAL";
    
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint securityConstraint = new SecurityConstraint();
                securityConstraint.setUserConstraint(USER_CONSTRAINT);
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                securityConstraint.addCollection(collection);
                context.addConstraint(securityConstraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }
    
    private Connector redirectConnector() {
        Connector connector = new Connector(
                TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setScheme(HTTP);
        connector.setPort(HTTP_PORT);
        connector.setSecure(false);
        connector.setRedirectPort(HTTPS_PORT);
        return connector;
    }
    

    귀하의 속성에서 설정하십시오. server.port = 443

  6. from https://stackoverflow.com/questions/30896234/how-set-up-spring-boot-to-run-https-http-ports by cc-by-sa and MIT license