springboot 2.1.6 版本 项目https改造


构建ca证书链

我们首先要创建 client/server 使用的证书。创建证书的方法有很多种:有不怕麻烦,直接通过openssl创建的,有通过 cfssl 创建的。这里要介绍的是我认为最简单的一种:tls-gen

tls-gen是一个用 Python 编写的、非常易用的工具。它定义了三种 profile。这里我们选择最简单的一种:一个根证书和一组证书、私钥对。

在 shell 里面执行一下的命令:

#注意需要的环境是python3.5+ 
git clone https://github.com/michaelklishin/tls-gen
cd tls-gen/basic
make PASSWORD=123456 DAYS_OF_VALIDITY=3650 CN=www.open-api.io

就这样,我们就为域名 www.open-api.io 创建了一套证书。观察一下当前路径的内容,我们会发现4个新的目录:testcaresultclientserver
前者里面存放了刚刚创建的根证书 (root CA),后者里面存放了我们服务程序要用的的证书和私钥。

  • cacert.cer:
    可以导入到浏览器中,然后就可以正常访问https页面
  • cacert.pem:
    各个 OS 添加根证书的方法是不同的。对于 Linux 系统 (以 Ubuntu 为例) 来说,把证书文件放到相应的目录即可:
sudo cp testca/cacert.pem /etc/ssl/certs
  • keycert.p12
    导入到springboot项目中

  • 查看别名

#查看证书的具体信息,包括tomcat必须用的别名
keytool -list -v -keystore keycert.p12 -storepass 123456
[root@localhost server]# tree ../server/
../server/
├── cert.pem
├── keycert.p12
├── key.pem
└── req.pem

0 directories, 4 files
[root@localhost server]# tree ../testca/
../testca/
├── cacert.cer
├── cacert.pem
├── certs
│   ├── 01.pem
│   └── 02.pem
├── index.txt
├── index.txt.attr
├── index.txt.attr.old
├── index.txt.old
├── private
│   └── cakey.pem
├── serial
└── serial.old

[root@localhost basic]# tree client/
client/
├── cert.pem
├── keycert.p12
├── key.pem
└── req.pem

0 directories, 4 files

服务器构建

修改properties配置文件
http.port=8080
# Define a custom port instead of the default 8080
server.port = 8443
# The format used for the keystore
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=classpath:keycert.p12
# The password used to generate the certificate
server.ssl.key-store-password=123456
# The alias mapped to the certificate
server.ssl.key-alias=1
修改Application代码
    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                // 如果要强制使用https,请松开以下注释
                 SecurityConstraint constraint = new SecurityConstraint();
                 constraint.setUserConstraint("CONFIDENTIAL");
                 SecurityCollection collection = new SecurityCollection();
                 collection.addPattern("/*");
                 constraint.addCollection(collection);
                 context.addConstraint(constraint);
            }
        };
        // 添加http
        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
        return tomcat;
    }
    
    // 配置http
    private Connector createStandardConnector() {
        // 默认协议为org.apache.coyote.http11.Http11NioProtocol
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setSecure(false);
        connector.setScheme("http");
        connector.setPort(port);
        // 当http重定向到https时的https端口号
        connector.setRedirectPort(httpsPort);
        return connector;
    }

客户端调用

这里用的client目录下的私钥

# 使用client目录下的私钥 keycert.p12
[root@localhost basic]# tree client/
client/
├── cert.pem
├── keycert.p12
├── key.pem
└── req.pem
编写RestTemplate
import com.google.common.collect.Lists;
import io.micrometer.core.instrument.util.StringUtils;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;
import java.io.InputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

/**
 * @date 2019-12-23 20:05:03
 * @since 1.0.0
 */
@Configuration
public class ServiceConfigConfiguration {

    @Autowired
    SSLProperties sslProperties;

    @Autowired
    ResourcePatternResolver resourcePatternResolver;

    /**
     * 访问SSL的Template
     *
     * @throws Exception
     */
    @Bean("sslRestTemplate")
    public RestTemplate tmsRestTemplate() throws Exception {
        //新建RestTemplate对象
        RestTemplate restTemplate = new RestTemplate();
        //判断证书文件地址是否存在
        if (StringUtils.isNotEmpty(sslProperties.getKeyfile())) {
            //在握手期间,如果URL的主机名和服务器的标识主机名不匹配,则验证机制可以回调此接口的实现程序来确定是否应该允许此连接
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            //构建SSL-Socket链接工厂
            SSLConnectionSocketFactory ssLSocketFactory = buildSSLSocketFactory("PKCS12",
                    sslProperties.getKeyfile(), sslProperties.getPassword(),
                    Lists.newArrayList("TLSv1"), true);
            //Spring提供HttpComponentsClientHttpRequestFactory指定使用HttpClient作为底层实现创建 HTTP请求
            HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                    HttpClients.custom().setSSLSocketFactory(ssLSocketFactory).build()
            );
            //设置传递数据超时时长
            httpRequestFactory.setReadTimeout(sslProperties.getTimeout());
            //设置建立连接超时时长
            httpRequestFactory.setConnectTimeout(sslProperties.getTimeout());
            //设置获取连接超时时长
            httpRequestFactory.setConnectionRequestTimeout(sslProperties.getTimeout());

            restTemplate.setRequestFactory(httpRequestFactory);

            // 返回消息头也是text_html,消息格式是XML,添加新的message converter
            Jaxb2RootElementHttpMessageConverter messageConverter = new Jaxb2RootElementHttpMessageConverter();
            //设置message Converter支持的媒体类型
            List finalMediaTypes = new ArrayList<>();
            finalMediaTypes.addAll(messageConverter.getSupportedMediaTypes());
            finalMediaTypes.add(MediaType.TEXT_HTML);
            messageConverter.setSupportedMediaTypes(finalMediaTypes);
            restTemplate.setMessageConverters(Lists.newArrayList(messageConverter));

        }
        return restTemplate;
    }

    /**
     * 构建SSLSocketFactory
     *
     * @param keyStoreType
     * @param keyFilePath
     * @param keyPassword
     * @param sslProtocols
     * @param auth         是否需要client默认相信不安全证书
     * @return
     * @throws Exception
     */
    private SSLConnectionSocketFactory buildSSLSocketFactory(String keyStoreType, String keyFilePath,
                                                             String keyPassword, List sslProtocols, boolean auth) throws Exception {
        //证书管理器,指定证书及证书类型
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        //KeyStore用于存放证书,创建对象时 指定交换数字证书的加密标准
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        InputStream inputStream = resourcePatternResolver.getResource(keyFilePath).getInputStream();
        try {
            //添加证书
            keyStore.load(inputStream, keyPassword.toCharArray());
        } finally {
            inputStream.close();
        }
        keyManagerFactory.init(keyStore, keyPassword.toCharArray());

        SSLContext sslContext = SSLContext.getInstance("SSL");
        if (auth) {
            // 设置信任证书(绕过TrustStore验证)
            TrustManager[] trustAllCerts = new TrustManager[1];
            TrustManager trustManager = new AuthX509TrustManager();
            trustAllCerts[0] = trustManager;
            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        } else {
            //加载证书材料,构建sslContext
            sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, keyPassword.toCharArray()).build();
        }

        SSLConnectionSocketFactory sslConnectionSocketFactory =
                new SSLConnectionSocketFactory(sslContext, sslProtocols.toArray(new String[sslProtocols.size()]),
                        null,
                        new HostnameVerifier() {
                            // 这里不校验hostname
                            @Override
                            public boolean verify(String urlHostName, SSLSession session) {
                                return true;
                            }
                        });

        return sslConnectionSocketFactory;
    }

    public class AuthX509TrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }
}
配置类 SSLProperties
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
@Data
public class SSLProperties {
    @Value("${open.api.ssl.client.keyfile}")
    private String keyfile;

    @Value("${open.api.ssl.client.password}")
    private String password;

    @Value("${open.api.ssl.client.timeout}")
    private int timeout;
}
配置文件
#客户端client配置
open.api.ssl.client.keyfile=classpath:client/keycert.p12
open.api.ssl.client.password=123456
open.api.ssl.client.timeout=10000
测试类
    @Resource(name = "sslRestTemplate")
    RestTemplate restTemplate;

    @Test
    public void testSslClient() {
        try {
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity response = restTemplate.getForEntity("https://www.open-api.io:8443/****", String.class);
            System.out.println(response.getBody());
        } catch (RestClientException e) {
            e.printStackTrace();
        }
    }

参看资料
Go代码打通HTTPs
SpringBoot配置http和https

你可能感兴趣的:(springboot 2.1.6 版本 项目https改造)