webflux token 验证 自定义注解
定义注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TokenAuth {
boolean validate() default true;
}
验证:
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class TokenFilter implements WebFilter {
@Resource
private RequestMappingHandlerMapping requestMappingHandlerMapping;
@Resource
private RRRRRR rrrrrr;
@Resource
private ZZZZZZZZ zzzz;
private boolean flag;
private String message;
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
// 获取Response、Request
ServerHttpResponse res = exchange.getResponse();
ServerHttpRequest req = exchange.getRequest();
// 判断是不是需要开启token验证
(读取配置文件是否开启验证,可删除掉)
// if (!zzzz.z1()) return chain.filter(exchange);
// 获取请求对应的HandlerMethod
Mono<HandlerMethod> handlerMethodMono = requestMappingHandlerMapping
.getHandler(exchange).cast(HandlerMethod.class);
handlerMethodMono.subscribe(handlerMethod -> {
// 判断方法头是否有注解
flag = handlerMethod.hasMethodAnnotation(TokenAuth.class);
if (!flag) return;
// 获取自定义注解里面的 validate 判断是否为false,如果是,则不验证
TokenAuth methodAnnotation = handlerMethod.getMethodAnnotation(TokenAuth.class);
if (methodAnnotation == null || methodAnnotation.validate() == false){
flag = false;
return;
}
// 获取 token信息,进行判断
HttpHeaders headers = req.getHeaders();
String token = headers.getFirst("token");
if (token != null){
// 开关控制,可以做一些逻辑判断,redis,其他判断
flag = false;
}
}).dispose();
if (!flag) return chain.filter(exchange);
// 返回
res.setStatusCode(HttpStatus.NON_AUTHORITATIVE_INFORMATION);
byte[] bytes = message.getBytes();
return res.writeWith(Mono.just(res.bufferFactory().wrap(bytes)));
}
}
测试:
@GetMapping(value = "")
@TokenAuth(validate = true)
public Mono<WapResponse<>> getXXXXXX() {
}