SpringCloud 实战:禁止直接访问后端服务

2021 年 2 月 5 日 CSDN

作者 | 单一色调     责编 | 张文
来源 | 转 载自 JAVA 日知录

前言


使用 SpringCloud 架构后,我们希望所有的请求都需要经过网关才能访问。在不作任何处理的情况下,我们是可以绕过网关直接访问后端服务的。如下,我们绕过网关直接访问后端服务也是可以获取到数据的。

那我们今天的议题就是如何防止请求绕过网关直接访问后端服务?


解决方案


我觉得防止绕过网关直接请求后端服务的解决方案主要有三种:
  • 使用 Kubernetes 部署
    在使用 Kubernetes 部署 SpringCloud 架构时,我们给网关的 Service 配置 NodePort,其他后端服务的 Service 使用 ClusterIp,这样在集群外就只能访问到网关了。
  • 网络隔离
    后端普通服务都部署在内网,通过防火墙策略限制只允许网关应用访问后端服务。
  • 应用层拦截
    请求后端服务时通过拦截器校验请求是否来自网关,如果不来自网关则提示不允许访问。
这里我们着重关注在应用层拦截这种解决方案。


实现


实现思路
实现思路其实也很简单,在请求经过网关的时候给请求头中增加一个额外的 Header,在后端服务中写一个拦截器,判断请求头是否与在网关设置的请求 Header 一致,如果不一致则不允许访问并给出提示。
当然为了防止在每个后端服务都需要编写这个拦截器,我们可以将其写在一个公共的 starter 中,让后端服务引用即可。而且为了灵活,可以通过配置决定是否只允许后端服务访问。
接下来我们看看核心代码。

实现过程

在网关 cloud-gateway 模块编写网关过滤器

       
       
         
@Component@Order(0)public class GatewayRequestFilter implements GlobalFilter {
@Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { byte[] token = Base64Utils.encode((CloudConstant.GATEWAY_TOKEN_VALUE).getBytes()); String[] headerValues = {new String(token)}; ServerHttpRequest build = exchange.getRequest() .mutate() .header(CloudConstant.GATEWAY_TOKEN_HEADER, headerValues) .build();
ServerWebExchange newExchange = exchange.mutate().request(build).build(); return chain.filter(newExchange); }
}
在请求经过网关时添加额外的 Header,为了方便这里直接设置成固定值。

建立公共 Starter 模块 cloud-component-security-starter

编写配置类,用于灵活控制服务是否允许绕过网关

       
       
         
@Data@ConfigurationProperties(prefix = "javadaily.cloud")public class CloudSecurityProperties {
/** * 是否只能通过网关获取资源 * 默认为True */ private Boolean onlyFetchByGateway = Boolean.TRUE;
}

编写拦截器,用于校验请求是否经过网关

       
       
         
public class ServerProtectInterceptor implements HandlerInterceptor {
private CloudSecurityProperties properties;
@Override public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler){
if (!properties.getOnlyFetchByGateway()) { return true; }
String token = request.getHeader(CloudConstant.GATEWAY_TOKEN_HEADER);
String gatewayToken = new String(Base64Utils.encode(CloudConstant.GATEWAY_TOKEN_VALUE.getBytes()));
if (StringUtils.equals(gatewayToken, token)) { return true; } else { ResultData<String> resultData = new ResultData<>(); resultData.setSuccess(false); resultData.setStatus(HttpServletResponse.SC_FORBIDDEN); resultData.setMessage("请通过网关访问资源"); WebUtils.writeJson(response,resultData); return false; } }
public void setProperties(CloudSecurityProperties properties) { this.properties = properties; }}

配置拦截器

       
       
         
public class CloudSecurityInterceptorConfigure implements WebMvcConfigurer {
private CloudSecurityProperties properties;
@Autowired public void setProperties(CloudSecurityProperties properties) { this.properties = properties; }
@Bean public HandlerInterceptor serverProtectInterceptor() { ServerProtectInterceptor interceptor = new ServerProtectInterceptor(); interceptor.setProperties(properties); return interceptor; }
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(serverProtectInterceptor()); }}

编写 starter 装载类

       
       
         
@EnableConfigurationProperties(CloudSecurityProperties.class)public class CloudSecurityAutoConfigure{
@Bean public CloudSecurityInterceptorConfigure cloudSecurityInterceptorConfigure() { return new CloudSecurityInterceptorConfigure(); }
}

建立资源文件 spring.factories,配置 Bean 的自动加载

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\   com.javadaily.component.security.configure.CloudSecurityAutoConfigure

在后端服务配置文件中添加属性配置,默认只能通过网关访问

       
       
         
javadaily:  cloud:    onlyFetchByGateway: true
经过以上几步,一个公共的 Starter 模块就构建完成了。

后端服务引用此公共 Starter 模块即可,以 account-service 为例

       
       
         
<dependency> <groupId>com.jianzh5.cloud</groupId> <artifactId>cloud-component-security-starter</artifactId></dependency>

实现效果

直接访问后端服务接口  
http://localhost:8010/account/getByCode/jianzh5
返回结果:
       
       
         
{  "message": "请通过网关访问资源",  "status": 403,  "success": false,  "timestamp": 1611660015830}
以上,希望对你有所帮助!

程序员如何避免陷入“内卷”、选择什么技术最有前景,中国开发者现状与技术趋势究竟是什么样?快来参与「2020 中国开发者大调查」,更有丰富奖品送不停!

☞小米澄清「手机不再支持GMS」;虾米音乐正式关停;《质量效应1》DLC 因源代码损坏而移除 | 极客头条

一行代码没写,凭啥被尊为“第一位程序员”?

程序员硬核“年终大扫除”,清理了数据库 70GB 空间

登录查看更多
4

相关内容

【2020新书】操作反模式: DevOps解决方案, 322页pdf
专知会员服务
30+阅读 · 2020年11月8日
【干货书】'Mastering Go 第二版中文版',143页pdf
专知会员服务
46+阅读 · 2020年11月1日
【2020新书】使用Kubernetes开发高级平台,519页pdf
专知会员服务
65+阅读 · 2020年9月19日
【2020新书】高级Python编程,620页pdf
专知会员服务
232+阅读 · 2020年7月31日
【2020新书】使用高级C# 提升你的编程技能,412页pdf
专知会员服务
56+阅读 · 2020年6月26日
【实用书】Python技术手册,第三版767页pdf
专知会员服务
228+阅读 · 2020年5月21日
TensorFlow Lite指南实战《TensorFlow Lite A primer》,附48页PPT
专知会员服务
68+阅读 · 2020年1月17日
【干货】大数据入门指南:Hadoop、Hive、Spark、 Storm等
专知会员服务
94+阅读 · 2019年12月4日
用 Python 开发 Excel 宏脚本的神器
私募工场
26+阅读 · 2019年9月8日
AWVS12 V12.0.190530102 windows正式版完美破解版
黑白之道
29+阅读 · 2019年8月24日
后渗透利用msf关闭防火墙
黑白之道
8+阅读 · 2019年8月24日
PHP使用Redis实现订阅发布与批量发送短信
安全优佳
7+阅读 · 2019年5月5日
百度开源项目OpenRASP快速上手指南
黑客技术与网络安全
5+阅读 · 2019年2月12日
kali实战渗透环境配置指南
黑白之道
5+阅读 · 2018年8月9日
我是一个爬虫
码农翻身
12+阅读 · 2018年6月4日
Python3爬虫之入门和正则表达式
全球人工智能
7+阅读 · 2017年10月9日
Python NLP 入门教程
开源中国
14+阅读 · 2017年10月1日
Arxiv
9+阅读 · 2016年10月27日
VIP会员
相关VIP内容
【2020新书】操作反模式: DevOps解决方案, 322页pdf
专知会员服务
30+阅读 · 2020年11月8日
【干货书】'Mastering Go 第二版中文版',143页pdf
专知会员服务
46+阅读 · 2020年11月1日
【2020新书】使用Kubernetes开发高级平台,519页pdf
专知会员服务
65+阅读 · 2020年9月19日
【2020新书】高级Python编程,620页pdf
专知会员服务
232+阅读 · 2020年7月31日
【2020新书】使用高级C# 提升你的编程技能,412页pdf
专知会员服务
56+阅读 · 2020年6月26日
【实用书】Python技术手册,第三版767页pdf
专知会员服务
228+阅读 · 2020年5月21日
TensorFlow Lite指南实战《TensorFlow Lite A primer》,附48页PPT
专知会员服务
68+阅读 · 2020年1月17日
【干货】大数据入门指南:Hadoop、Hive、Spark、 Storm等
专知会员服务
94+阅读 · 2019年12月4日
相关资讯
用 Python 开发 Excel 宏脚本的神器
私募工场
26+阅读 · 2019年9月8日
AWVS12 V12.0.190530102 windows正式版完美破解版
黑白之道
29+阅读 · 2019年8月24日
后渗透利用msf关闭防火墙
黑白之道
8+阅读 · 2019年8月24日
PHP使用Redis实现订阅发布与批量发送短信
安全优佳
7+阅读 · 2019年5月5日
百度开源项目OpenRASP快速上手指南
黑客技术与网络安全
5+阅读 · 2019年2月12日
kali实战渗透环境配置指南
黑白之道
5+阅读 · 2018年8月9日
我是一个爬虫
码农翻身
12+阅读 · 2018年6月4日
Python3爬虫之入门和正则表达式
全球人工智能
7+阅读 · 2017年10月9日
Python NLP 入门教程
开源中国
14+阅读 · 2017年10月1日
Top
微信扫码咨询专知VIP会员