文章目录
前言
通过配置spring cloud gateway实现服务https定制软件访问及下游服务的路由更改
一、使用场景
定制软件在某些第三方接口调用定制软件场景下需要提供https定制软件安全访问链接,定制软件例微信小程序的接口开发中,定制软件强制要求为https请求接口,本篇内容为通过阿里云安全证书+spring cloud gateway访问配置实现服务接口的https安全访问。
二、使用步骤
1.下载阿里云SSL安全证书
登录个人账号信息,进入阿里云管理后台,点击跳转至SSL证书模块,选择免费证书(首次需要创建),点击下载,选择tomcat版本证书,下载的文件包含.pfx的证书文件和.txt的密码文件
2.证书配置
代码如下(示例):进入gateway网关服务,将下载的证书解压后添加至resource资源目录下,证书名称可进行自定义,然后在yaml配置中添加如下内容
- server:
- ssl:
- enable: true
- key-store: classpath: 自定义ssl证书文件
- key-store-type: PKCS12
- key-store-password: 阿里云下载证书对应密码
此时便可通过https访问到gateway服务
3.gateway服务设置后台微服务访问方式
通过上述配置步骤,虽然网关可以正常访问,但是在通过gateway访问其他服务时报错。由于进来时是https请求,在gateway转发给其他微服务时依然是https请求,这时可通过将其他服务也设置成https访问,即每个服务都进行配置ssl,同时采用域名进行注册服务,这无疑工作量很大。
使用过Zuul的都知道,Zuul默认会将https请求自动转为http请求给后台微服务,而gateway只需进行相应的配置便可实现同等功能。
第一种、修改gateway的配置:
- spring:
- cloud:
- gateway:
- routes: #配置路由路径
- - id: oauth2-server
- # 之前路由为 uri: lb://oauth2-server
- uri: lb:http://oauth2-server
第二种、添加过滤器(原理相同):
- import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
-
- import java.net.URI;
-
- import org.springframework.cloud.gateway.filter.GatewayFilterChain;
- import org.springframework.cloud.gateway.filter.GlobalFilter;
- import org.springframework.core.Ordered;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import org.springframework.web.util.UriComponentsBuilder;
-
- import reactor.core.publisher.Mono;
-
-
- @Component
- public class SchemeFilter implements GlobalFilter, Ordered {
-
- @Override
- public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
- Object uriObj = exchange.getAttributes().get(GATEWAY_REQUEST_URL_ATTR);
- if (uriObj != null) {
- URI uri = (URI) uriObj;
- uri = this.upgradeConnection(uri, "http");
- exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);
- }
- return chain.filter(exchange);
- }
-
- private URI upgradeConnection(URI uri, String scheme) {
- UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUri(uri).scheme(scheme);
- if (uri.getRawQuery() != null) {
- // When building the URI, UriComponentsBuilder verify the allowed characters and does not
- // support the '+' so we replace it for its equivalent '%20'.
- // See issue https://jira.spring.io/browse/SPR-10172
- uriComponentsBuilder.replaceQuery(uri.getRawQuery().replace("+", "%20"));
- }
- return uriComponentsBuilder.build(true).toUri();
- }
-
- @Override
- public int getOrder() {
- return 10101;
- }
- }
总结
通过以上配置,便可实现gateway及gateway的https请求。