Spring Boot 如何同时支持 http 与 https 访问?

原文链接:Spring Boot 如何同时支持 http 与 https 访问?


大多数项目要么要求 https 协议来访问要么直接用 http 协议,但有些项目就是这么奇怪要求同时支持两种协议。

此示例中使用Spring Boot 内置的 tomcat 服务器,我拿到的 SSL 证书是 crt 类型的。所有首先需要将证书转成 jks 类型的。

crt 转 jks

  # 转p12
  openssl pkcs12 -export -out keystore.pkcs12 -inkey nexus.key -in nexus.crt
	
  # 这里需要设置密码
  # 再将p12格式文件转为.jks格式:
  keytool -v -importkeystore -srckeystore keystore.pkcs12 -srcstoretype PKCS12 -destkeystore 
  keystore.jks -deststoretype JKS
  # 输入上步设置的密码并设置新密码 可以和上一步一样的密码

Windows 系统需要安装 openssl 后才可以执行上述命令。

安装

将生成的 jks 文件放到项目的 resource 目录下,开始配置 application.yml 文件。

server:
  port: 8888
  custom:
    # http 端口
    httpPort: 9999
  ssl:
    key-store: classpath:keystore.jks
    key-password: 123456
    key-store-type: JKS
  tomcat:
    uri-encoding: utf-8
    basedir: tmp
  #
  servlet:
    context-path: /

然后编写 Https配置类:HttpConfig.java

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: ChangXuan
 * @Decription: 配置同时支持 HTTP 与 HTTPS 访问
 * @Date: 19:39 2020/2/20
 **/
@Configuration
public class HttpsConfig {
    @Value("${server.custom.httpPort}")
    private Integer httpPort;

    @Bean
    public ServletWebServerFactory serverFactory() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(createStandardConnector());
        return tomcat;
    }
    /**
     * 配置http
     * @return
     */
    private Connector createStandardConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setPort(httpPort);
        return connector;
    }
}

注意事项

application.yml 中配置的 jks 文件的目录为 classpath ,classpath 指的是 target/classes 目录。所以运行时如果报错“找不到 jks 文件”,就手动将 jks 文件复制到此目录下一份。

已标记关键词 清除标记
Spring Boot httphttps 为啥在配置文件中已经配置了,还是不能自动转? keystore.p12也已经生成,项目已经配置支持https协议。 application.properties的配置: server.port=8443 spring.thymeleaf.cache=false security.require-ssl=true server.ssl.key-store=keystore.p12 server.ssl.key-store-password=111111 server.ssl.keyStoreType=JKS server.ssl.keyAlias:tomcat 这是我的配置文件: ``` 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.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.PropertySource; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.io.File; import java.util.ArrayList; import java.util.List; @Controller @SpringBootApplication public class ThymeleafTestApplication<T> { @RequestMapping("/index") public String index(Model model){ Person single=new Person("aa",1); List<Person> people=new ArrayList<Person>(); Person p1=new Person("bb",2); Person p2=new Person("cc",3); Person p3=new Person("dd",4); people.add(p1); people.add(p2); people.add(p3); model.addAttribute("singlePerson",single); model.addAttribute("people",people); return "index"; } //实现http协议转https协议的配置 @Bean public EmbeddedServletContainerFactory servletContainer(){ TomcatEmbeddedServletContainerFactory tomcat=new TomcatEmbeddedServletContainerFactory(){ @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint=new SecurityConstraint(); securityConstraint.setDisplayName("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); connector.setSecure(false); connector.setRedirectPort(8443); return connector; } public static void main(String[] args) { SpringApplication.run(ThymeleafTestApplication.class, args); } } ```
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页