1.生成证书。
keytool -genkey -alias tomcat -keypass 12345678 -keyalg RSA -keysize 2048 -validity 365 -keystore ./tomcat.keystore -storepass 12345678
2.生成客户端证书
keytool -genkey -alias client -keypass 12345678 -keyalg RSA -keysize 2048 -validity 365 -storetype PKCS12 -keystore ./client.p12 -storepass 12345678
3.修改配置
1.打开已有的SpringBoot工程
2.将证书文件:client.p12复制到resources目录下
3.修改application.yml
server:
port: 8443 #注意,这里是https访问的的端口号
ssl:
key-store: file:F:\Study\mywebsite\websiteback\src\main\resources\client.p12
key-store-password: 12345678
key-store-type: PKCS12
key-alias: client
4.修改启动类
添加servletContainer()和initiateHttpConnector()两个方法,完整代码如下:
package com.jipson.websiteback;
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.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@MapperScan({"com.jipson.websiteback.dao"})
public class WebsitebackApplication {
public static void main(String[] args) {
SpringApplication.run(WebsitebackApplication.class, args);
}
@Bean
public TomcatServletWebServerFactory servletContainer() { //springboot2 新变化
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(initiateHttpConnector());
return tomcat;
}
private Connector initiateHttpConnector() {
Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(8080);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
}
6.其他
当我们使用程序访问的时候可能还不行。需要把我们要访问的地址复制到浏览器中。在浏览器中打开的时候会提示我们证书可能不合法。信任即可。后面就可以正常的访问了。