satoken+webflux获取header以及body

简介: satoken+webflux获取header以及body


你若要喜爱自己的价值,你就得给世界创造价值。——歌德

代码如下:

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.SaTokenContextForThreadLocalStorage;
import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.reactor.filter.SaReactorFilter;
import cn.dev33.satoken.router.SaRouter;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.Objects;
/**
 * SaReactorFilter
 *
 * @author achao@apache.org
 */
@Component
public class SaReactorFilter extends SaReactorFilter {
    @Lazy
    @Resource
    private DataBufferFactory dataBufferFactory;
    @Resource
    private AgoraProperties agoraProperties;
    public SaReactorReactorFilter() {
        // 拦截所有路由
        addInclude("/**");
        setAuth(router -> {
            SaRouter.match("/api/rtc/**").check(r -> {
                // 获取header中的值
                var token = SaTokenContextForThreadLocalStorage.getRequest().getHeader("token");
                if (token == null) {
                    throw new ApiClientException("请检查请求头是否包含token");
                }
                // 获取body
                var requestBody = SaHolder.getStorage().get("requestBody", "");
                if (requestBody == null) {
                    throw new ApiClientException("请检查请求体是否为空");
                }
            });
        });
    }
    @Bean
    public DataBufferFactory dataBufferFactory() {
        return new DefaultDataBufferFactory();
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        SaReactorSyncHolder.setContext(exchange);
        return DataBufferUtils.join(exchange.getRequest().getBody())
                .flatMap(dataBuffer -> {
                    String requestBody = DataBufferUtil.dataBufferToString(dataBuffer);
                    SaHolder.getStorage().set("requestBody", requestBody);
                    ServerHttpRequestDecorator decoratedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
                        public @Override @NotNull Flux<DataBuffer> getBody() {
                            return Flux.just(dataBufferFactory.wrap(requestBody.getBytes()));
                        }
                    };
                    return super.filter(exchange.mutate().request(decoratedRequest).build(), chain);
                });
    }
}

对应的DataBufferUtil

import lombok.experimental.UtilityClass;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import java.nio.charset.StandardCharsets;
/**
 * DataBufferUtil
 *
 * @author achao@apache.org
 */
@UtilityClass
public final class DataBufferUtil {
    public static String dataBufferToString(DataBuffer dataBuffer) {
        byte[] bytes = new byte[dataBuffer.readableByteCount()];
        dataBuffer.read(bytes);
        DataBufferUtils.release(dataBuffer); // 释放DataBuffer资源
        return new String(bytes, StandardCharsets.UTF_8);
    }
}
import lombok.experimental.UtilityClass;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import java.nio.charset.StandardCharsets;
/**
 * DataBufferUtil
 *
 * @author achao@apache.org
 */
@UtilityClass
public final class DataBufferUtil {
    public static String dataBufferToString(DataBuffer dataBuffer) {
        byte[] bytes = new byte[dataBuffer.readableByteCount()];
        dataBuffer.read(bytes);
        DataBufferUtils.release(dataBuffer); // 释放DataBuffer资源
        return new String(bytes, StandardCharsets.UTF_8);
    }
}
相关文章
|
6月前
|
JSON 前端开发 Java
前端请求SpringBoot接口出现Required request body is missing
前端请求SpringBoot接口出现Required request body is missing
311 2
|
XML JSON 数据处理
postman 中 body的form-data,x-www-form-urlencoded,raw,binary含义
postman 中 body的form-data,x-www-form-urlencoded,raw,binary含义
503 0
postman 中 body的form-data,x-www-form-urlencoded,raw,binary含义
|
5月前
|
XML 数据格式
Jsoup获取部分页面数据失败 org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, appl
Jsoup获取部分页面数据失败 org.jsoup.UnsupportedMimeTypeException: Unhandled content type. Must be text/*, appl
46 2
SpringCloud Feign报错Method has too many Body parameters
SpringCloud Feign报错Method has too many Body parameters
Spring Boot 一个接口同时支持 form 表单、form-data、json 优雅写法
网上很多代码都是千篇一律的 cvs,相信我只要你认真看完我写的这篇,你就可以完全掌握这个知识点,这篇文章不适合直接 cvs,一定要先理解。
head 插件 Content-Type header [application/x-www-form-urlencoded] is not supported
head 插件 Content-Type header [application/x-www-form-urlencoded] is not supported
134 1
报错 An error happened during template parsing (template: “ServletContext resource [/shiroTest.html]“)
报错 An error happened during template parsing (template: “ServletContext resource [/shiroTest.html]“)
|
数据采集 大数据 应用服务中间件
Lua 获取 Header 与 Body 数据|学习笔记
快速学习 Lua 获取 Header 与 Body 数据
Lua 获取 Header 与 Body 数据|学习笔记
|
XML JSON Java
SpringMVC报错:HTTP Status 405 - JSPs only permit GET POST or HEAD
SpringMVC报错:HTTP Status 405 - JSPs only permit GET POST or HEAD
272 0
SpringMVC报错:HTTP Status 405 - JSPs only permit GET POST or HEAD
|
Web App开发 JSON 编解码
我又踩坑了!如何为HttpClient请求设置Content-Type标头?
小编对于Http协议有知识漏洞,搬砖时一直关注Chrome DevTools,忽略了还有Entity Header一说
我又踩坑了!如何为HttpClient请求设置Content-Type标头?