Spring cloud gateway 设置https 和http同时支持

              Spring cloud gateway 处理跨域问题

              Spring cloud gateway 拦截请求404 等HTTP 状态码

              Spring cloud gateway 修改response 截断问题,乱码问题解决

              Spring cloud gateway 详解和配置使用(文章较长) 

              Spring cloud Gateway 指定执行过滤器 (在配置文件中配置所需要过滤器)

话不多说,直接上硬货: 

这是gateway 官网的配置截图

   这个配置简单,但是我们需要同时支持http 和https

目前这个问题官方还没有正式解决

https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.2.RELEASE/reference/html/#tls-and-ssl

https://github.com/spring-cloud/spring-cloud-gateway/issues/1103

民间人士,想到的办法是 在启动一个Netty 监听另外一个端口 如:8080,这个端口是不带 s 的也就是   http

当访问8080时 跳转到配置https 的如8443端口 

经过一番查找

https://github.com/spring-projects/spring-boot/issues/12035

https://stackoverflow.com/questions/49045670/spring-webflux-redirect-http-to-https/53000573#53000573

具体实现:

package cn.com.test.gateway.config;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import reactor.core.publisher.Mono;
 
import javax.annotation.PostConstruct;
import java.net.URI;
import java.net.URISyntaxException;

@Configuration
public class HttpToHttpsRedirectConfig {

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

    @PostConstruct
    public void startRedirectServer() {
        NettyReactiveWebServerFactory httpNettyReactiveWebServerFactory = new NettyReactiveWebServerFactory(httpPort);
        httpNettyReactiveWebServerFactory.getWebServer((request, response) -> {
            URI uri = request.getURI();
            URI httpsUri;
            try {
                httpsUri = new URI("https", uri.getUserInfo(), uri.getHost(), serverPort, uri.getPath(), uri.getQuery(), uri.getFragment());
            } catch (URISyntaxException e) {
                return Mono.error(e);
            }
            response.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
            response.getHeaders().setLocation(httpsUri);
            return response.setComplete();
        }).start();
    }


}

yml 配置文件配置:

分为俩个端口号,server.port 是配置https 的端口, http.port 是监听的端口

server:
  http:
    port: 4321
  port: 1234
  ssl:
    enabled: true
    key-alias: scg
    key-store: classpath:ssl/test.pfx
    key-store-password: 6540CNd4Whw
    keyStoreType: PKCS12

目录结构: 

 启动后访问,不带s 的4321端口会转发到1234端口。

记得双击摸摸哒!

一键三连摸摸哒!

### Spring Cloud Gateway HTTPSHTTP 配置 在 Spring Cloud Gateway 中实现将 HTTPS 请求转换为 HTTP 请求的功能,可以通过自定义路由规则以及修改网关的行为来完成。以下是具体的配置方法: #### 1. 修改 `application.yml` 或 `application.properties` 为了使 Spring Cloud Gateway 将外部的 HTTPS 流量内部重定向到 HTTP 协议的服务端口上,可以调整如下属性: ```yaml server: port: 8443 # 设置服务器监听的 HTTPS 端口号 spring: cloud: gateway: routes: - id: http_to_https_route uri: http://localhost:8080 # 目标服务地址 (HTTP) predicates: - Path=/example/** # 定义匹配路径 ``` 上述配置中指定了一个名为 `http_to_https_route` 的路由规则[^5],它会拦截 `/example/` 开头的所有请求并将这些请求转发至目标 URI (`http://localhost:8080`)。 #### 2. 启用 SSL 支持 为了让 Spring Cloud Gateway 接收 HTTPS 请求,在应用启动时需加载证书文件。这通常涉及以下步骤: - **添加依赖项** 如果尚未引入必要的安全库,则需要更新项目的 Maven POM 文件以包含 Jetty 或 Tomcat 提供的支持包之一: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <!-- 如果使用 Jetty --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> </dependency> ``` - **配置 keystore truststore 参数** 接着,在 `application.yml` 中指定密钥存储位置及其密码信息: ```yaml server: ssl: key-store-type: PKCS12 key-store: classpath:keystore.p12 key-password: secret enabled: true ``` 此部分设置了用于加密通信的数据源,并启用了 SSL 功能[^6]。 #### 3. 自定义过滤器处理协议切换逻辑 有时仅靠简单的 URL 映射无法满足需求场景下的复杂业务流程控制;此时可通过编写自定义全局过滤器或者局部过滤器进一步增强功能特性。下面展示了一个例子——创建一个新的类继承抽象基类 AbstractGatewayFilterFactory<T> 来实现特定行为模式: ```java import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; public class ProtocolConversionFilter extends AbstractGatewayFilterFactory<ProtocolConversionFilter.Config> { public static class Config { private String targetScheme = "http"; public void setTargetScheme(String scheme){ this.targetScheme=scheme; } public String getTargetScheme(){ return this.targetScheme; } } @Override public GatewayFilter apply(Config config) { return ((exchange, chain) -> { exchange.getRequest().mutate() .scheme(config.getTargetScheme()) .build(); return chain.filter(exchange); }); } } ``` 之后就可以像其他预设好的工厂那样注册该实例对象了[^7]: ```yaml spring: cloud: gateway: globalcors: corsConfigurations: '[/**]': allowedOrigins: "*" allowedMethods: - GET - POST default-filters: - name: ProtocolConversionFilter args: _targetScheme_: 'http' ``` 以上代码片段展示了如何构建一个能够改变原始请求 Scheme 属性值的新类型 Filter 并将其应用于整个应用程序之中。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值