应用使用HTTPS
Spring boot 项目使用https ,本文将实现自定义密钥和将HTTP重定向到HTTPS功能,或者直接使用https访问系统,暂不支持证书下发
- 自定义密钥
- 自定义密钥
/**
* https密钥
*/
public static void pkcKey() {
String[] commands = new String[]{
"cmd",
"/k",
//cmd Shell命令
"start",
"keytool",
//genkey表示生成密钥
"-genkey",
//别名
"-alias", "tomcat",
//store类型
"-storetype", "PKCS12",
//加密算法
"-keyalg", "RSA",
//密钥大小
"-keysize", "2048",
//key位置
"-keystore", "D:/account.p12",
//证书有效期(单位:天)
"-validity", "3650",
//密钥库密码,至少为6位
"-storepass", "123456",
//别名条目密码
"-keypass", "123456",
//CN=名字与姓氏,OU=组织单位名称,O=组织名称,L=城市或区域名 称,ST=州或省份名称,C=单位的两字母国家代码
"-dname",
"CN=(WQ),OU=(WQ),O=(WQ),L=(BJ),ST=(BJ),C=(CN)",
//显示证书详情
"-v"
};
try {
execCommand(commands);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 执行cmd命令
* @param commands
* @throws IOException
*/
public static void execCommand(String... commands) throws IOException {
Runtime.getRuntime().exec(commands);
}
- 配置文件
http:
port: 1314
server:
port: 520
ssl:
key-store: D:/account.p12
key-store-type: PKCS12
key-password: 123456
key-store-password: 123456
- 将HTTP重定向到HTTPS
/**
* @author weiQiang
*/
@Configuration
public class AccountConfig {
@Value("${http.port}")
private Integer httpPort;
@Value("${server.port}")
private Integer serverPort;
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() {
@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(initiateHttpConnector());
return tomcat;
}
/**
* HTTP重定向到HTTPS
*
* @return
*/
private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(httpPort);
connector.setSecure(false);
connector.setRedirectPort(serverPort);
return connector;
}
}