您的位置:

SpringBoot Https实现

一、前言

在互联网时代,隐私和安全问题愈发突出,SpringBoot Https实现正是应对这一趋势的重要解决方案。通过本文,你将学到如下内容:

1. Https与Http的区别

2. Https的作用及优缺点

3. SpringBoot Https实现方法和步骤

二、Https介绍

Https(Hyper Text Transfer Protocol over Secure Socket Layer)即在HTTP上添加SSL层,将HTTP包装起来,从而保护数据传输过程中的隐私和安全,实现了加密通信和身份认证。

相较于Http,Https的优点有:

1. 数据传输过程中的隐私和安全更加可靠;

2. 可以防止中间人攻击(Man-in-the-Middle Attack);

3. 能够校验证书,确保服务器与客户端的真实性和一致性;

4. 能够对SEO产生积极影响。

三、SpringBoot Https实现步骤

1. 生成证书和私钥

使用Java提供的keytool工具生成证书和私钥。示例命令:

   keytool -genkeypair -alias tomcat \
   -keyalg RSA -keysize 2048 \
   -keystore your_keystore_name.jks \
   -validity 3650

其中,tomcat代表别名,keysize代表密钥长度,keystore代表证书存储路径。根据实际情况进行修改即可。

2. 配置application.properties

添加以下内容:

   server.port=443
   server.ssl.key-store=classpath:your_keystore_name.jks
   server.ssl.key-store-password=your_keystore_password
   server.ssl.keyStoreType=JKS
   server.ssl.keyAlias=tomcat

其中,port指定了服务器的端口号为443,key-store-path指定生成的证书路径,key-store-password指定证书密码,key-store-type指定证书类型,keyAlias指定了生成证书时的别名。

3. 修改启动类

在启动类中添加@EnableAutoConfiguration注解,并修改configure方法为下列代码:

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       http.authorizeRequests().anyRequest().permitAll()
               .and().csrf().disable()
               .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
               .and().httpBasic().disable()
               .headers().cacheControl().disable();
   }

在这里,我们允许所有请求都被通过,每次登录的session不需要管理,禁用了HTTP的基本认证验证,并禁用了响应头信息的缓存控制。

四、开启Https验证

通过以上配置后,启动SpringBoot项目默认为http,在访问https时会提示Http请求无法访问。我们还需要为SpringBoot添加Https支持,使请求能够被Https处理。

在启动类Application的main方法中添加如下内容即可启用Https验证:

   Ssl ssl = new Ssl();
   ssl.setKeyStore("classpath:your_keystore_name.jks");
   ssl.setKeyStorePassword("your_keystore_password");
   ssl.setKeyAlias("tomcat");
   TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
   tomcat.addAdditionalTomcatConnectors(createSslConnector());
   tomcat.setSsl(ssl);
   return tomcat;
}

private Connector createSslConnector() {
   Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
   Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
   try {
       File truststore = new ClassPathResource("your_keystore_name.jks").getFile();
       connector.setScheme("https");
       connector.setSecure(true);
       connector.setPort(8443);
       protocol.setSSLEnabled(true);
       protocol.setKeystoreFile(truststore.getAbsolutePath());
       protocol.setKeystorePass("your_keystore_password");
       protocol.setKeyAlias("tomcat");
       return connector;
   }
   catch (IOException ex) {
       throw new IllegalStateException("can't access truststore: " + ex);
   }
}

五、完整代码示例

以下为完整的SpringBoot Https实现代码示例:

@SpringBootApplication
public class Application extends SpringBootServletInitializer {
   public static void main(String[] args) {
       SpringApplication.run(Application.class, args);
   }
   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
       Ssl ssl = new Ssl();
       ssl.setKeyStore("classpath:your_keystore_name.jks");
       ssl.setKeyStorePassword("your_keystore_password");
       ssl.setKeyAlias("tomcat");
       TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
       tomcat.addAdditionalTomcatConnectors(createSslConnector());
       tomcat.setSsl(ssl);
       return builder.sources(Application.class).web(WebApplicationType.SERVLET)
               .bannerMode(Banner.Mode.OFF)
               .properties("spring.config.additional-location=classpath:/application-production.properties")
               .properties("spring.output.ansi.enabled=ALWAYS")
               .properties("server.port=80")
               .properties("server.http.port=80")
               .properties("server.https.port=443")
               .properties("server.ssl.enabled=true")
               .properties("server.ssl.client-auth=none")
               .properties("server.ssl.key-store=classpath:your_keystore_name.jks")
               .properties("server.ssl.key-store-password=your_keystore_password")
               .properties("server.ssl.keyStoreType=JKS")
               .properties("server.ssl.keyAlias=tomcat")
               .serverCustomizers((TomcatServletWebServerFactory factory) -> {
                   factory.addConnectorCustomizers((connector) -> {
                       connector.setProperty("relaxedQueryChars", "|{}[]");
                       connector.setParseBodyMethods("POST,PUT,DELETE");
                       connector.setProperty("relaxedPathChars", "_[]{}|");
                   });
               });
   }
   private Connector createSslConnector() {
       Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
       Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
       try {
           File truststore = new ClassPathResource("your_keystore_name.jks").getFile();
           connector.setScheme("https");
           connector.setSecure(true);
           connector.setPort(443);
           protocol.setSSLEnabled(true);
           protocol.setKeystoreFile(truststore.getAbsolutePath());
           protocol.setKeystorePass("your_keystore_password");
           protocol.setKeyAlias("tomcat");
           return connector;
       }
       catch (IOException ex) {
           throw new IllegalStateException("can't access truststore: " + ex);
       }
   }
}

六、小结

通过本文,我们了解到Https的优点和作用,并详细介绍了SpringBoot中实现Https的步骤和代码示例。对于项目安全和隐私保护的需求,开启Https是一种可行的解决方案。