webflux切面拦截权限,webflux整合aop,webflux获取request

背景

在springboot+tomcat应用中获取request对象可以使用RequestContextHolder.getRequestAttributes()的方式来获取,此种方式的核心在于request所在容器被放在threadlocal中,但是webflux结合netty项目却不能这么使用,因为webflux是异步响应式的,下面介绍下异步服务webflux+netty如何便捷获取request。

编写基于webflux的RequestContextHolder实现

  1. 编写ReactiveHttpContextHolder类用来模拟RequestContextHolder
public class ReactiveHttpContextHolder {
    //获取当前请求对象
    public static Mono<ServerHttpRequest> getRequest() {
        return Mono.subscriberContext()
                .map(context -> context.get(Info.CONTEXT_KEY).getRequest());
    }

    //获取当前response
    public static Mono<ServerHttpResponse> getResponse(){
        return Mono.subscriberContext()
                .map(context -> context.get(Info.CONTEXT_KEY).getResponse());
    }

    public static final class Info{
        public static final Class<ServerWebExchange> CONTEXT_KEY = ServerWebExchange.class;
    }
}
  1. 编写过滤器类用于设置request到容器中
@Component
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
public class AppFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        //设置当前请求
         return chain.filter(exchange)
                .subscriberContext(context -> context.put(ReactiveHttpContextHolder.Info.CONTEXT_KEY, exchange));
    }
}

编写切面实现token拦截,校验权限

  1. 切面逻辑代码
@Component
@Aspect
public class AuthAspect extends BaseController {

    @Pointcut("execution(public * xx.xx.xxController.*(..))")
    private void classRule(){}
    //带有AuthIgnore注解的不校验
    @Pointcut("@annotation(xx.AuthIgnore)")
    private void ignoreRule(){}

    @Around("classRule() && !ignoreRule()")
    public Mono<Object> aroundInvoke(ProceedingJoinPoint joinPoint){
        //获取token
        Mono<ServerHttpRequest> requestMono = ReactiveHttpContextHolder.getRequest();
        return requestMono.flatMap(request -> {
            //检查token
            String token = getHeader("token", request);
            if (token == null || TokenCacheContainer.getTokenCache().get(token) == null){
                BusException ex = new BusException("01300001");
                return buildErrMsg(ex);
            } else {
                try {
                    return (Mono<Object>) joinPoint.proceed();
                } catch (Throwable throwable) {
                    LogFactory.getLog(AuthAspect.class).error("", throwable);
                    BusException ex = new BusException("01300000");
                    return buildErrMsg(ex);
                }
            }
        });
    }

    private Mono<String> buildErrMsg(BusException ex){
        ApiJsonResult errResult = ApiJsonResult.createErrResult(ex.getErrorCode(), ex.getReason(), ex.getResolve());
        return Mono.just( errResult.toString() );
    }
}
  1. 说明
    过滤器会在切面之前执行,因此aop中能获取到在filter中设置的request
  2. 测试结果
    在这里插入图片描述
Spring AOP(面向切面编程)中,获取HTTP请求的body通常是在处理Controller层的处理器方法之前或之后的操作。如果你想拦截并操作HTTP请求体,可以创建一个切面(Aspect),然后使用`@Around`通知或`@Before`/`@AfterReturning`通知。 首先,你需要定义一个自定义注解,比如`@ProcessRequestBody`: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ProcessRequestBody { } ``` 然后,在切面类中,使用`@Around`方法来拦截那些带有该注解的方法,并从`HttpServletRequest`中获取请求体: ```java import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class RequestBodyAspect { @Around("@annotation(ProcessRequestBody)") public Object processRequestBody(ProceedingJoinPoint joinPoint) throws Throwable { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); // 这里假设请求体是一个String,可以根据实际需要转换 String requestBody = request.getReader().lines().collect(Collectors.joining("\n")); try { // 执行原方法 return joinPoint.proceed(); } finally { // 关闭资源 if (request.getReader() != null) { request.getReader().close(); } } } } ``` 记得将这个切面添加到SpringAOP扫描路径中,以便它能自动应用到目标类上。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值