webflux token 验证 自定义注解

本文介绍了一种使用Spring WebFlux实现的自定义Token验证机制。通过定义TokenAuth注解来控制方法级别的验证,并在TokenFilter中实现了具体的验证逻辑。文章详细展示了如何根据注解属性决定是否进行验证,以及如何从请求头中获取并验证Token。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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() {
  
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值