springcloud gateway 针对某些路由跳过全局过滤器,有什么方法吗?

2020-07-21 20:44:34 +08:00
 Augustine1128

请问各位大佬,springcloud gateway 针对某些路由跳过全局过滤器,有什么方法吗?

网上看了一些方法,都是向请求的 attributes 里放参数,然后全局过滤器依据这些参数决定做不做鉴权,我觉得不太安全(恶意请求也可以向请求头里面放这些参数),请问有什么比较好的方法?

2169 次点击
所在节点    程序员
13 条回复
retanoj
2020-07-21 20:48:36 +08:00
所以,需求是正确嘛?
Augustine1128
2020-07-21 20:50:15 +08:00
@retanoj 不太明白您的意思,您是说需求不合理吗?其实想做的就是除了注册登录,其他都要做鉴权。
limuyan44
2020-07-21 21:12:12 +08:00
可以采用针对某几个 url 进行拦截,未登录时,再怎么伪造请求,某些 url 都会校验的,至于登录之后一般都会存在某些 token 。
Augustine1128
2020-07-21 21:19:00 +08:00
@limuyan44 这样就要在代码里把某些 url 写死?总感觉这样不够优雅😂
StevenTong
2020-07-21 21:44:10 +08:00
写两个 filter,一个用来全局移除前端传过来的 header,一个给指定路由加你要的 header,保证就算恶意请求过来携带了 header 也不管用。
limuyan44
2020-07-21 21:51:34 +08:00
@Augustine1128 配置写在配置中心或者配置文件是通常的作法,不存在硬编码在类中的情况。
Augustine1128
2020-07-21 22:52:15 +08:00
@StevenTong 这个可以考虑一下
Augustine1128
2020-07-21 22:54:13 +08:00
@limuyan44 好的,谢谢指点
xuanbg
2020-07-22 09:11:00 +08:00
写个 url 配置表放在 redis 里面,这个表搞一个是否验证的字段,过滤器根据这个字段来决定直接放行还是验证身份权限。如果访问的 url 都不存在表里面,就可以直接拦回去了。
myCupOfTea
2020-07-22 15:35:40 +08:00
获取配置
@Component
@ConfigurationProperties(prefix = "gateway")
public class GatewayConfig {


private String[] excludesUrls;

public String[] getExcludesUrls() {
return excludesUrls;
}

public void setExcludesUrls(String[] excludesUrls) {
this.excludesUrls = excludesUrls;
}
}

添加不鉴权的接口

@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers().frameOptions().disable();
http.csrf().disable()
.authorizeRequests()
.antMatchers("/test/**", "swagger-ui**").permitAll()
.and().addFilterBefore(new TokenAuthFilter(permissionClient, redisService,
new String[]{"/api/**"},
excludesUrls.getExcludesUrls()),
UsernamePasswordAuthenticationFilter.class);

}

当然 TokenAuthFilter 继承 GenericFilterBean 实现的

不难的
配置中心的配置文件

gateway:
excludesUrls:
- /api/user/auth/**
- /api/cms/content/editorUpload
- /api/file/downloadFileByUri
- /api/file/previewFileByUri
StevenTong
2020-07-22 15:44:00 +08:00
@myCupOfTea spring cloud gateway 是 webflux 的,security 也是 webflux security,跟你提供的代码实现上会有一些差别。楼主想跳过 gatewayfilter 吧,不是 securityfilter
Augustine1128
2020-07-23 00:43:11 +08:00
@StevenTong 想跳过的其实是 globlefilter
myCupOfTea
2020-07-23 09:12:17 +08:00
@StevenTong 反正本质上就是读配置加 filter 就行了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/692027

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX