|
| 1 | +package net.codingme.https.config; |
| 2 | + |
| 3 | +import org.apache.catalina.Context; |
| 4 | +import org.apache.catalina.connector.Connector; |
| 5 | +import org.apache.tomcat.util.descriptor.web.SecurityCollection; |
| 6 | +import org.apache.tomcat.util.descriptor.web.SecurityConstraint; |
| 7 | +import org.springframework.beans.factory.annotation.Value; |
| 8 | +import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; |
| 9 | +import org.springframework.context.annotation.Bean; |
| 10 | +import org.springframework.context.annotation.Configuration; |
| 11 | + |
| 12 | +/** |
| 13 | + * <p> |
| 14 | + * HTTP 强制跳转 HTTPS |
| 15 | + * |
| 16 | + * @Author niujinpeng |
| 17 | + * @Date 2019/4/21 17:47 |
| 18 | + */ |
| 19 | +@Configuration |
| 20 | +public class Http2Https { |
| 21 | + |
| 22 | + @Value("${server.port}") |
| 23 | + private int sslPort; |
| 24 | + @Value("${server.http-port}") |
| 25 | + private int httpPort; |
| 26 | + |
| 27 | + @Bean |
| 28 | + public TomcatServletWebServerFactory servletContainerFactory() { |
| 29 | + TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() { |
| 30 | + @Override |
| 31 | + protected void postProcessContext(Context context) { |
| 32 | + SecurityConstraint securityConstraint = new SecurityConstraint(); |
| 33 | + securityConstraint.setUserConstraint("CONFIDENTIAL"); |
| 34 | + SecurityCollection collection = new SecurityCollection(); |
| 35 | + collection.addPattern("/*"); |
| 36 | + securityConstraint.addCollection(collection); |
| 37 | + context.addConstraint(securityConstraint); |
| 38 | + } |
| 39 | + }; |
| 40 | + Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); |
| 41 | + connector.setScheme("http"); |
| 42 | + connector.setPort(httpPort); |
| 43 | + connector.setRedirectPort(sslPort); |
| 44 | + tomcat.addAdditionalTomcatConnectors(connector); |
| 45 | + return tomcat; |
| 46 | + } |
| 47 | +} |
0 commit comments