方式一:直接编写一个过滤工厂,重写方法编写过滤器
方式二:编写过滤器工厂,再写一个过滤器类实现gatewayfilter重写方法
package sca.pro.gateway.common.auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
/**
* @author shq
* @description 自定义token认证过滤器工厂
* @createDate 2022-5-25
* @updateUser
* @updateDate
* @updateRemark
*/
@Component
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {
@Autowired
private AuthGatewayFilter authGatewayFilter;
@Override
public GatewayFilter apply(Object config) {
return authGatewayFilter;
}
}
package sca.pro.gateway.common.auth;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import sca.pro.common.contants.Contants;
/**
* @author shq
* @description 身份认证过滤器
* @createDate 2022-5-25
* @updateUser
* @updateDate
* @updateRemark
*/
@Component
public class AuthGatewayFilter implements GatewayFilter, Ordered {
/**
* 排序规则
*
* @return
*/
@Override
public int getOrder() {
return -100;
}
/**
* jwt全局过滤器
*
* @param exchange
* @param chain
* @return
*/
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
MultiValueMap<String, String> headers = exchange.getRequest().getHeaders();
if (!CollectionUtils.isEmpty(headers) && headers.containsKey(Contants.HEADER_LOGIN_INFO_BASE64_KEY)) {
ServerHttpRequest host = exchange.getRequest().mutate().header(Contants.HEADER_LOGIN_INFO_BASE64_KEY, null).build();
exchange = exchange.mutate().request(host).build();
}
return chain.filter(exchange);
}
}
注意这里的配置文件,过滤器的填写格式,就是定义的过滤器工厂类的前缀,比如咱们是AuthGatewayFilterFactory,那么在配置文件就要写成Auth,例如:
spring:
cloud:
gateway:
routes:
- id: sca-jwt-local
uri: lb://sca-jwt-local
predicates:
- Path=/jwt/**
filters:
//当配置了 StripPrefix=1 过滤器后,如果请求的路径中存在前缀路径,该过滤器将会去除指定数量的前缀路径。具体而言,StripPrefix=1 表示去除请求路径的第一个路径片段(即前缀路径)
//当收到形如 /jwt/users 的请求时,StripPrefix=1 将会去除 /api 前缀,将最终的请求路径转发到http://sca-jwt-local/users
- StripPrefix=1
- Auth
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
routes:
default-filters:
- DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-
Credentials,
globalcors:
cors-configurations:
'[/**]':
allowed-origins: "*"
allowed-methods: "*"
allowed-headers: "x-requested-with,Content-Language,Authorization,token,Access-Control-Allow-Origin,request-id,Accept-Language,content-type,content-disposition"
allow-credentials: true
到此全局过滤器已经定义完成了
下边来看一下限流的方式