Springboot设置Https

1、修改配置文件application.yml,并将*.jks放到resource目录下。

server:
  port: 8080
  ssl:
    key-store: classpath:*.jks
    key-store-password: *
    key-store-type: JKS
    enabled: true
    key-alias: boe.com.cn

2、添加http转https的配置

@Configuration
public class TomcatConfig {
    @Bean
    public TomcatServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() {
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        tomcat.addAdditionalTomcatConnectors(httpConnector());
        return tomcat;
    }

    @Bean
    public Connector httpConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        //Connector监听的http的端口号
        connector.setPort(8082);
        connector.setSecure(false);
        //监听到http的端口号后转向到的https的端口号
        connector.setRedirectPort(8080);
        return connector;
    }
}

3、修改pom.xml文件
一般到上一步,本地运行没有什么问题,但是打包会有问题。

<plugin>
    <groupId>org.apache.maven.pluginsgroupId>
    <artifactId>maven-resources-pluginartifactId>
    <version>3.1.0version>
    <configuration>
        <nonFilteredFileExtensions>
            
            <nonFilteredFileExtension>jksnonFilteredFileExtension>
        nonFilteredFileExtensions>
    configuration>
plugin>

此时打包应该没有问题,但是部署时可能会出现端口问题,如果出现就添加一下代码

<resource>
  <directory>src/main/resourcesdirectory>
  <filtering>truefiltering>
  <excludes>
      
      <exclude>*.jksexclude>
  excludes>
resource>
<resource>
  <directory>src/main/resourcesdirectory>
  <filtering>falsefiltering>
  <includes>
      
      <include>*.jksinclude>
  includes>
resource>

另外,如果还有问题,就很可能是端口问题,8090这个端口配置一直不成功,换成8080就好了。

你可能感兴趣的:(spring,boot,https,后端)