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

Easter79
• 阅读 468

1 简介

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

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

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

(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 如何做到重定向

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

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

3 Springboot Tomcat实现重定向

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

主类的代码如下:

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.porthttps端口;http.porthttp端口。注意在没有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以Tomcat为容器实现http重定向到https的两种方式

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

参考链接:

Spring Security: https://docs.spring.io/spring-security/site/docs/5.3.2.BUILD-SNAPSHOT/reference/html5/#servlet-http-redirect

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


欢迎访问南瓜慢说 www.pkslow.com获取更多精彩文章!

欢迎关注微信公众号<**南瓜慢说**>,将持续为你更新...

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

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
2个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k