比如我们使用jwt的时候,判断是否有token
给router的handler加过滤
@Order
@Component
public class AuthFilter implements HandlerFilterFunction {
@Override
public Mono filter(ServerRequest request, HandlerFunction next) {
String path = request.uri().getPath();
if (path.equals("/login")) {
return next.handle(request);
}
String token = request.headers().firstHeader("token");
if (StringUtils.isEmpty(token)) {
Map<String, Object> map = new HashMap<>();
map.put("data", null);
map.put("code", -1);
map.put("msg", "miss token");
return ok().contentType(MediaType.APPLICATION_JSON).body(map, Map.class);
}
return next.handle(request);
}
}
下面是加全局过滤,包括router方式与controller方式都会触发
@Component
public class CustomWebFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange serverWebExchange, WebFilterChain webFilterChain) {
PathPattern pattern=new PathPatternParser().parse("/login");
ServerHttpRequest request=serverWebExchange.getRequest();
if (pattern.matches(request.getPath().pathWithinApplication())){
System.out.println("custom webFilter");
}
return webFilterChain.filter(serverWebExchange);
}
}