SpringBoot配置HTTPS與HTTP同時使用

  • 生成證書
keytool -genkey -alias tomcathttps -keyalg RSA -keysize 2048 -keystore Batac.p12 -validity 365
  • 放在項目根目錄下

 

  • 配置文件
server.ssl.key-store=Batac.p12
server.ssl.key-alias=tomcathttps
server.ssl.key-store-password=123456
  • 創建接口
  • @RestController
    public class HelloController {
    
        @GetMapping("/hello")
        public String hello(){
            return "Hello World";
        }
    
    }

    訪問 https://localhost:8080/hello 成功!

         此時 http://localhost:8080/hello 就無法訪問;

  • 由於SpringBoot不支持同時再配置中啓動HTTP和HTTPS。 這個時候可以配置重定向, 將HTTP請求重定向爲HTTPS請求。配置如下:
  • @Configuration
    public class TomcatConfig {
    
        @Bean
        TomcatServletWebServerFactory tomcatServletWebServerFactory(){
            TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
                @Override
                protected void postProcessContext(Context context){
                    SecurityConstraint constraint = new SecurityConstraint();
                    constraint.setUserConstraint("CONFIDENTIAL");
                    SecurityCollection collection = new SecurityCollection();
                    collection.addPattern("/*");
                    constraint.addCollection(collection);
                    context.addConstraint(constraint);
                }
            };
            factory.addAdditionalTomcatConnectors(createTomcatConnector());
            return factory;
        }
    
        private Connector createTomcatConnector(){
            Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
            connector.setScheme("http");
            //設置http訪問接口
            connector.setPort(8081);
            connector.setSecure(false);
            //重定向到https接口
            connector.setRedirectPort(8080);
            return connector;
        }
    }

    當訪問http://localhost:8081/hello的時候, 就會自動跳轉到https://localhost:8080/hello

  • 結束

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章