转:
spring cloud gateway自定义过滤器
关键点:
3、局部过滤器,需要实现GatewayFilter, Ordered,实现相关的方法
package com.yefengyu.gateway.localFilter; import com.yefengyu.gateway.utitls.AuthUtil; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.core.Ordered; import org.springframework.http.HttpStatus; import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Mono; public class AuthGatewayFilter implements GatewayFilter, Ordered { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { //获取header的参数 String name = exchange.getRequest().getHeaders().getFirst("name"); String password = exchange.getRequest().getHeaders().getFirst("password"); boolean permitted = AuthUtil.isPermitted(name, password);//权限比较 if (permitted) { return chain.filter(exchange); } else { exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); return exchange.getResponse().setComplete(); } } @Override public int getOrder() { return 10; } }
4、接着需要把上面自定义的局部过滤器加入到过滤器工厂,并且注册到spring容器中。
package com.yefengyu.gateway.localFilter; import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.stereotype.Component; @Component public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> { @Override public GatewayFilter apply(Object config) { return new AuthGatewayFilter(); } }
5、在配置文件中进行配置,如果不配置则不启用此过滤器规则。
【配置文件这里只要写 AuthGatewayFilter 类名中GatewayFilter前面的部分就行】