# https 設定 1. 產生 SSL certificate >keytool -genkey -alias tomcat -storetype PKCS12 -keyalg RSA -keysize 2048 -keystore keystore.p12 -validity 3650 > <font color="#f00">這個 certificate 是 self-signed certificate 沒有經過第三方認證, 所以沒有公信力,正式上線會在瀏覽器看到 連線不被信任 </font> 2. application.properies 設定參考 >#https端口号. server.port: 8443 #证书的路径. server.ssl.key-store: classpath:keystore.p12 #证书密码,请修改为您自己证书的密码. server.ssl.key-store-password: springboot #秘钥库类型 server.ssl.keyStoreType: PKCS12 #证书别名 server.ssl.keyAlias: tomcat security.require-ssl=true > 3. Redirect HTTP requests to HTTPS ```java= @Configuration public class ServerConfig { @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(TomcatServletWebServerFactory.DEFAULT_PROTOCOL); connector.setScheme("http"); connector.setPort(8080); connector.setSecure(false); connector.setRedirectPort(8443); return connector; } } ``` 4. Spring Security ```java= @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .requiresChannel() .anyRequest() .requiresSecure(); } } ``` --- 資料來源: [How to enable HTTPS in a Spring Boot Java application](https://www.thomasvitale.com/https-spring-boot-ssl-certificate/) [apache-tomcat 8.5 SSL證書佈置及強制https](https://www.itread01.com/content/1543125544.html) [Nginx 設定 https 連線](https://xyz.cinc.biz/2017/06/nginx-https-ssl.html) [NGINX 設定 HTTPS 網頁加密連線,建立自行簽署的 SSL 憑證](https://blog.gtwang.org/linux/nginx-create-and-install-ssl-certificate-on-ubuntu-linux/) [靈活多變的keytool和openssl生成證書,應用tomcat和nginx](https://www.itread01.com/content/1541037805.html#testkeystoretestjks_182) [如何使用 OpenSSL 建立開發測試用途的自簽憑證 (Self-Signed Certificate)](https://blog.miniasp.com/post/2019/02/25/Creating-Self-signed-Certificate-using-OpenSSL) [使用 Let’s Encrypt 取得 SSL 來設定 HTTPS 並強制使用 SSL 安全加密協定](https://polinwei.com/use-lets-encrypt-to-get-free-ssl-certificate/) [Spring Boot 配置 SSL 憑證 jks & p12 的設定](https://polinwei.com/spring-boot-ssl-certificate-configure/) ###### tags: `Spring boot` `https` `tomcat` `Nginx` `openssl` `ssl for free`