编写自定义的权限校验代码,并且使该过滤器在指定的路由上生效即可如果权限校验需要使用到redis,则在gateway中需要引入redis的依赖
自定义token权限校验代码
public class AppTokenFilter implements GatewayFilter, Ordered {
private static final Logger logger = LoggerFactory.getLogger(AppTokenFilter.class);
private int order;
private TokenRedis tokenRedis;
private static final List<String> NO_FILTER_PATHS = new ArrayList<>();
static{
NO_FILTER_PATHS.add("/game-app-server-api/api/v1/account/register/rapid");
NO_FILTER_PATHS.add("/game-app-server-api/api/v1/account/register/mobile");
NO_FILTER_PATHS.add("/game-app-server-api/api/v1/account/login/account");
NO_FILTER_PATHS.add("/game-app-server-api/api/v1/account/login/mobile");
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
logger.info("AppTokenFilter ...");
PathContainer pathContainer = exchange.getRequest().getPath().pathWithinApplication();
String path = pathContainer.toString();
if(NO_FILTER_PATHS.contains(path)){
return chain.filter(exchange);
}
if(tokenRedis == null){
tokenRedis = SpringUtils.getBean(TokenRedis.class);
}
List<String> headers = exchange.getRequest().getHeaders().get("token");
String token = headers != null ? headers.get(0) : "";
logger.info(">>>>>>> token:{} >>>>>>>>", token);
UserInfoBo u = tokenRedis.getUserInfoByToken(token);
logger.info(">>>>>>> userId:{} >>>>>>>>", u != null ? u.getUserId() : null);
if(u == null){
return exchange.getResponse().writeWith(Flux.just(exchange.getResponse()
.bufferFactory().wrap(JsonUtils.Object2Json(R.error(ErrorCode.SYS_USER_NOT_LOGIN)).getBytes())) );
}else{
return chain.filter(exchange);
}
}
@Override
public int getOrder() {
return this.order;
}
public AppTokenFilter(int order){
this.order = order;
}
}
配置自定义的ApptokenFilter到指定的路由上
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator appRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/game-app-server-api/api/**")
.filters(f -> f.filter(new AppTokenFilter(-10)))
.uri("lb://game-app-server-api")
.id("game-app-server-api")
).build();
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-2465.html