Spring Boot开启https

原文:https://github.com/x113773/testall/issues/1

1. 第一步就是用JDK的keytool工具来创建一个密钥存储(keystore)
`keytool -keystore mykeys.jks -genkey -alias tomcat -keyalg RSA`
记住输入的Enter keystore password(该项目为letmein),剩下的一路回车,直到:
` Is CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown correct?`
输入yes

2. 把证书添加到项目中
[`src/main/resources/mykeys.jks`](https://github.com/x113773/testall/blob/master/src/main/resources/mykeys.jks)

3. 修改配置文件application.properties,加入如下配置
```
server.port= 8443
server.ssl.key-store= classpath:mykeys.jks
server.ssl.key-store-password= letmein
server.ssl.key-password= letmein

```

4. 配置用户访问http自动跳转到https
[HttpsConfiguration.java](https://github.com/x113773/testall/blob/master/src/main/java/com/ansel/testall/config/HttpsConfiguration.java)
```
import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpsConfiguration {

@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(){
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(httpConnector());
return tomcat;
}

@Bean
public Connector httpConnector(){
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);//表示用8080端口来供http访问
connector.setSecure(false);
connector.setRedirectPort(8443);//自动重定向到8443端口
return connector;
}
}
```

上一篇:Ubuntu12.04下载Repo


下一篇:【jQuery UI 1.8 The User Interface Library for jQuery】.学习笔记.8.Datepicker控件