- 生成证书
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
-
结束