Springboot以Tomcat为容器实现http重定向到https的两种方式

本文涉及的产品
容器镜像服务 ACR,镜像仓库100个 不限时长
简介:

Springboot以Tomcat为容器实现http重定向到https的两种方式

1 简介
本文将介绍在Springboot中如何通过代码实现Http到Https的重定向,本文仅讲解Tomcat作为容器的情况,其它容器将在以后一一道来。

建议阅读之前的相关文章:

(1) Springboot整合https原来这么简单

(2)HTTPS之密钥知识与密钥工具Keytool和Keystore-Explorer

2 相关概念
2.1 什么叫重定向
所谓重定向,就是本来你想浏览地址A的,但是到达服务端后,服务端认为地址A的界面不在了或者你没权限访问等原因,不想你访问地址A;就告诉你另一个地址B,然后你再去访问地址B。

对于重定向一般有两个返回码:

301:永久性重定向;
302:暂时性重定向。
通过Chrome查看网络详情,记录了几个网站的重定向情况:

网站 域名 重定向代码 重定向后的网址
南瓜慢说 www.pkslow.com 301 https://www.pkslow.com
Google www.google.com 307 https://www.google.com
Apple www.apple.com 307 https://www.apple.com
支付宝 www.alipay.com 301 https://www.alipay.com
QQ www.qq.com 302 https://www.qq.com
百度 www.baidu.com 307 https://www.baidu.com
注:307也是重定向的一种,是新的状态码。

2.2 为什么要重定向
结合我上面特意列的表格,是不是大概想到了为何要做这种重定向?不难发现上面的重定向都在做一件事,就是把http重定向为https。原因如下:

(1)http是不安全的,应该使用安全的https网址;

(2)但不能要求用户每次输入网站都输入https:// 吧,这也太麻烦了,所以大家都是习惯于只输入域名,甚至连www. 都不愿意输入。因此,用户的输入其实都是访问http的网页,就需要重定向到https以达到安全访问的要求。

2.3 如何做到重定向
首先,服务器必须要同时支持http和https,不然也就没有重定向一说了。因为https是必须提供支持的,那为何还要提供http的服务呢?直接访问https不就行了,不是多此一举吗?原因之前已经讲过了,大家是习惯于只输入简单域名访问的,这时到达的就是http,如果不提供http的支持,用户还以为你的网站已经挂了呢。

两种协议都提供支持,所以是需要打开两个Socket端口的,一般http为80,而https为443。然后就需要把所有访问http的请求,重定向到https即可。不同的服务器有不同的实现,现在介绍Springboot+Tomcat的实现。

3 Springboot Tomcat实现重定向
Springboot以Tomcat作为Servlet容器时,有两种方式可以实现重定向,一种是没有使用Spring Security的,另一种是使用了Spring Security的。代码结构如下:

主类的代码如下:

package com.pkslow.ssl;

import com.pkslow.ssl.config.containerfactory.HttpToHttpsContainerFactoryConfig;
import com.pkslow.ssl.config.security.EnableHttpWithHttpsConfig;
import com.pkslow.ssl.config.security.HttpToHttpsWebSecurityConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

@SpringBootApplication
@Import({EnableHttpWithHttpsConfig.class, HttpToHttpsWebSecurityConfig.class})
//@Import(HttpToHttpsContainerFactoryConfig.class)
@ComponentScan(basePackages = "com.pkslow.ssl.controller")
public class SpringbootSslApplication {

public static void main(String[] args) {
    SpringApplication.run(SpringbootSslApplication.class, args);
}

}
@ComponentScan(basePackages = "com.pkslow.ssl.controller"):没有把config包扫描进来,是因为想通过@Import来控制使用哪种方式来进行重定向。当然还可以使用其它方式来控制,如@ConditionalOnProperty,这里就不展开讲了。

当没有使用Spring Security时,使用@Import(HttpToHttpsContainerFactoryConfig.class);

当使用Spring Security时,使用@Import({EnableHttpWithHttpsConfig.class, HttpToHttpsWebSecurityConfig.class})。

配置文件application.properties内容如下:

server.port=443
http.port=80

server.ssl.enabled=true
server.ssl.key-store-type=jks
server.ssl.key-store=classpath:localhost.jks
server.ssl.key-store-password=changeit
server.ssl.key-alias=localhost
需要指定两个端口,server.port为https端口;http.port为http端口。注意在没有https的情况下,server.port指的是http端口。

3.1 配置Container Factory实现重定向
配置的类为HttpToHttpsContainerFactoryConfig,代码如下:

package com.pkslow.ssl.config.containerfactory;

import org.apache.catalina.Context;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpToHttpsContainerFactoryConfig {

@Value("${server.port}")
private int httpsPort;

@Value("${http.port}")
private int httpPort;

@Bean
public TomcatServletWebServerFactory servletContainer() {
    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(createHttpConnector());
    return tomcat;
}

private Connector createHttpConnector() {
    Connector connector =
            new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
    connector.setScheme("http");
    connector.setSecure(false);
    connector.setPort(httpPort);
    connector.setRedirectPort(httpsPort);
    return connector;
}

}
createHttpConnector():这个方法主要是实现了在有https前提下,打开http的功能,并配置重定向的https的端口。

3.2 配置Spring security实现重定向
有两个配置类,一个为打开http服务,一个为实现重定向。

EnableHttpWithHttpsConfig主要作用是在已经有https的前提下,还要打开http服务。

package com.pkslow.ssl.config.security;

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.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
public class EnableHttpWithHttpsConfig {

@Value("${http.port}")
private int httpPort;

@Component
public class CustomContainer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        Connector connector = new Connector(TomcatServletWebServerFactory.DEFAULT_PROTOCOL);
        connector.setPort(httpPort);
        connector.setScheme("http");
        connector.setSecure(false);
        factory.addAdditionalTomcatConnectors(connector);
    }
}

}
HttpToHttpsWebSecurityConfig主要是针对Spring Security的配置,众所周知,Spring Security是功能十分强大,但又很复杂的。代码中已经写了关键的注释:

package com.pkslow.ssl.config.security;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class HttpToHttpsWebSecurityConfig extends WebSecurityConfigurerAdapter {

@Value("${server.port}")
private int httpsPort;

@Value("${http.port}")
private int httpPort;

@Override
protected void configure(HttpSecurity http) throws Exception {
    //redirect to https - 用spring security实现
    http.portMapper().http(httpPort).mapsTo(httpsPort);
    http.requiresChannel(
            channel -> channel.anyRequest().requiresSecure()
    );

    //访问路径/hello不用登陆获得权限
    http.authorizeRequests()
            .antMatchers("/hello").permitAll()
            .anyRequest().authenticated().and();
}

@Override
public void configure(WebSecurity web) throws Exception {
    //过滤了actuator后,不会重定向,也不用权限校验,这个功能非常有用
    web.ignoring()
            .antMatchers("/actuator")
            .antMatchers("/actuator/**");
}

}
4 总结
最后实现了重定向,结果展示:

本文详细代码可在南瓜慢说公众号回复获取。

参考链接:

Springboot 1.4重定向:https://jonaspfeifer.de/redirect-http-https-spring-boot/

原文地址https://www.cnblogs.com/larrydpk/p/12806699.html

相关文章
|
2月前
|
监控 Java 应用服务中间件
Spring Boot整合Tomcat底层源码分析
【11月更文挑战第20天】Spring Boot是一个用于快速构建基于Spring框架的应用程序的开源框架。它通过自动配置和起步依赖等特性,大大简化了Spring应用的开发和部署过程。本文将深入探讨Spring Boot的背景历史、业务场景、功能点以及底层原理,并通过Java代码手写模拟Spring Boot的启动过程,特别是其与Tomcat的整合。
71 1
|
3月前
|
缓存 安全 网络协议
HTTP和HTTPS的区别有哪些?
本文简要总结了 HTTP 和 HTTPS 的区别,从概念、端口、连接方式、使用场景、安全性等多个角度进行了对比。HTTP 是无状态的、无连接的应用层协议,适用于一般性网站和性能要求较高的应用;HTTPS 则通过 SSL/TLS 层提供加密、认证和完整性保护,适用于涉及敏感信息和高安全性的场景。文章还讨论了两者在性能上的差异,包括握手和加密开销、缓存效果以及 HTTP/2 的多路复用技术。最终,根据具体需求选择合适的协议能够更好地平衡安全性和性能。
600 2
HTTP和HTTPS的区别有哪些?
|
2月前
|
前端开发 JavaScript 安全
前端性能调优:HTTP/2与HTTPS在Web加速中的应用
【10月更文挑战第27天】本文介绍了HTTP/2和HTTPS在前端性能调优中的应用。通过多路复用、服务器推送和头部压缩等特性,HTTP/2显著提升了Web性能。同时,HTTPS确保了数据传输的安全性。文章提供了示例代码,展示了如何使用Node.js创建一个HTTP/2服务器。
79 3
|
18天前
|
应用服务中间件 Linux 网络安全
nginx安装部署ssl证书,同时支持http与https方式访问
为了使HTTP服务支持HTTPS访问,需生成并安装SSL证书,并确保Nginx支持SSL模块。首先,在`/usr/local/nginx`目录下生成RSA密钥、证书申请文件及自签名证书。接着,确认Nginx已安装SSL模块,若未安装则重新编译Nginx加入该模块。最后,编辑`nginx.conf`配置文件,启用并配置HTTPS服务器部分,指定证书路径和监听端口(如20000),保存后重启Nginx完成部署。
237 7
|
22天前
|
安全 算法 网络安全
HTTP和HTTPS的区别
本文介绍HTTP与HTTPS的区别、HTTPS链接建立过程及常见加密算法。HTTP为明文传输,易被窃听;HTTPS通过SSL/TLS协议加密,确保数据安全。HTTPS使用端口443,提供认证机制。文中还详细讲解了对称加密(如AES、DES)和非对称加密(如RSA、ECC)算法的特点及应用场景。
|
2月前
|
缓存 安全 网络安全
HTTP/2与HTTPS在Web加速中的应用
HTTP/2与HTTPS在Web加速中的应用
|
28天前
|
安全 网络安全 数据安全/隐私保护
第六问:http和https区别与联系
HTTP 和 HTTPS 是现代网络通信中的两种重要协议。HTTP 是明文传输协议,无加密功能;HTTPS 在 HTTP 基础上加入 SSL/TLS 加密层,提供数据加密、身份验证和数据完整性保障。HTTP 适用于非敏感信息传输,如新闻网站;HTTPS 适用于在线支付、账户登录等需要保护用户数据的场景。
42 0
|
2月前
|
前端开发 JavaScript 数据库
https页面加载http资源的解决方法
https页面加载http资源的解决方法
70 5
|
3月前
|
Java 网络架构 Kotlin
kotlin+springboot入门级别教程,教你如何用kotlin和springboot搭建http
本文是一个入门级教程,介绍了如何使用Kotlin和Spring Boot搭建HTTP服务,并强调了Kotlin的空安全性特性。
111 7
kotlin+springboot入门级别教程,教你如何用kotlin和springboot搭建http
|
2月前
|
前端开发 安全 应用服务中间件
前端性能调优:HTTP/2与HTTPS在Web加速中的应用
【10月更文挑战第26天】随着互联网的快速发展,前端性能调优成为开发者的重要任务。本文探讨了HTTP/2与HTTPS在前端性能优化中的应用,介绍了二进制分帧、多路复用和服务器推送等特性,并通过Nginx配置示例展示了如何启用HTTP/2和HTTPS,以提升Web应用的性能和安全性。
45 3