代码步骤:
① 网关模块里 创建一个类并实现 GlobalFilter 接口
@Order(-1) //值越小,优先级越高。也可以实现Ordered接口指定优先级
@Component //注入到 Spring 容器
public class AuthorizeFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//1.获取请求参数
ServerHttpRequest request = exchange.getRequest();//拿到 request 对象
MultiValueMap<String, String> params = request.getQueryParams(); //key:参数名称 value:对应的值
//2.获取参数中的 authorization 参数
String auth = params.getFirst("authorization");
//3.判断参数值是否等于 admin,相等就放行,不相等就拦截
if ("admin".equals(auth)) {//放行
return chain.filter(exchange);
} else {//拦截
//设置状态码,让用户看起来更友好
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
}
}
标签:网关,return,chain,exchange,request,参数,过滤器,Gateway From: https://www.cnblogs.com/gagaya2/p/17850508.html