非对称加密实战(三):http和https可一并访问加入拦截器【附源码】

问题描述

根据上面非对称加密实战(二):解决web项目不支持https问题 【附源码】来讲,配好https后,http是无法访问的,那么要进行处理的话,需要加入拦截器,来进行https跳转
在这里插入图片描述

解决方案

在服务端加入拦截器,拦截所有的http请求重定向到https请求

修改application.yml

添加http端口

# http端口
http-port: 8082
# https端口
server:
  port: 8081

  ssl:
    key-store: classpath:fd-alias.keystore
    key-store-type: JKS
    key-alias: fd-alias
    key-store-password: 123456
    key-password: 123456

加入拦截器,拦截所有请求

	package com.springweb.intercept;

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.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * http强制跳转https
 */
@Configuration
public class HttpToHttps {

    // https的端口
    @Value("${server.port}")
    private int sslPort;

    // http的端口
    @Value("${http-port}")
    private int httpPort;

    @Bean
    public TomcatServletWebServerFactory servletContainerFactory() {
        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);
            }
        };
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        //遇到http进行转发
        connector.setScheme("http");

        //true: http使用http, https使用https;
        //false: http重定向到https;
        connector.setSecure(false);

        // 设置http端口
        connector.setPort(httpPort);

        //重定向端口号(非SSL到SSL)
        connector.setRedirectPort(sslPort);

        tomcat.addAdditionalTomcatConnectors(connector);
        return tomcat;
    }
}

我们直接请求8082端口,会直接跳转到8081端口,附截图

在这里插入图片描述
在这里插入图片描述

源码地址

公钥私钥-拦截器 github

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无奈的码农

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值