spring cloud gateway权限校验
spring cloud gateway权限校验可以整合security实现,我这里采用自定义filter简单实现,步骤如下:1.首先配置RouteLocator,贴代码@Configurationpublic class GatewayRoutes {@Autowiredprivate TokenGatewayFilter tokenGatewayFilter;@B...
·
spring cloud gateway权限校验可以整合security实现,我这里采用自定义filter简单实现,步骤如下:
1.首先配置RouteLocator,贴代码
@Configuration
public class GatewayRoutes {
@Autowired
private TokenGatewayFilter tokenGatewayFilter;
@Bean
public RouteLocator biRouteLocator(RouteLocatorBuilder builder) {
//重定向替换
RewritePathGatewayFilterFactory.Config config = new RewritePathGatewayFilterFactory.Config();
config.setRegexp("/bi/(?<segment>.*)");
config.setReplacement("/${segment}");
GatewayFilter rewritePathGatewayFilter = new RewritePathGatewayFilterFactory()
.apply(config);
Function<GatewayFilterSpec, UriSpec> fn = gatewayFilterSpec -> gatewayFilterSpec.filter(rewritePathGatewayFilter).filter(tokenGatewayFilter)
.hystrix(hysConfig -> hysConfig
.setName("bi")
.setFallbackUri("forward:/fallback"));
return builder.routes()
//basic proxy
.route("bi",p -> p.path("/bi/**")
//导入配置
.filters(fn)
.uri("lb://bi-service")
).build();
}
}
2.自定义filter,在filter校验权限,并返回结果
@Component
public class TokenGatewayFilter implements GatewayFilter ,Ordered{
@Override
public int getOrder() {
return 0;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String token = null;
//从header取
token = exchange.getRequest().getHeaders().getFirst("Authorization");
if(StringUtils.isEmpty(token)){
//尝试从param取
token = exchange.getRequest().getQueryParams().getFirst("token");
}
//尝试从cookies取
if(StringUtils.isEmpty(token)){
HttpCookie cookies = exchange.getRequest().getCookies().getFirst("token");
if(cookies!=null){
token = cookies.getValue();
}
}
if(StringUtils.isEmpty(token)){
return responseFailRs(exchange, RespResult.create(401,"token参数未传入"));
}
//TODO 校验jwt token
return chain.filter(exchange);
}
private Mono<Void> responseFailRs(ServerWebExchange exchange,RespResult RespResult) {
ServerHttpResponse serverHttpResponse = exchange.getResponse();
serverHttpResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
byte[] bytes = RespResult.toString().getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
return serverHttpResponse.writeWith(Flux.just(buffer));
}
}
源码地址 https://github.com/fdqzq613/myframe.git
更多推荐
已为社区贡献1条内容
所有评论(0)