You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WebFlux中获取HTTP Header实现Spring Data审计

WebFlux 下从HTTP Header提取用户ID实现Spring Data审计(无Spring Security)

1. 确保ServerWebExchangeContextFilter生效

这个过滤器是Spring WebFlux自带组件,用于将ServerWebExchange存入Reactor Context。Spring Boot 2.x+通常会自动配置,若需手动注册可添加以下配置:

@Configuration
public class WebConfig {
    @Bean
    public ServerWebExchangeContextFilter serverWebExchangeContextFilter() {
        return new ServerWebExchangeContextFilter();
    }
}

2. 自定义过滤器提取Header并写入Reactor Context

编写WebFilter从请求Header中取出用户ID,存入Reactor Context供后续审计组件读取:

@Component
public class UserIdContextFilter implements WebFilter {
    private static final String USER_ID_HEADER = "X-USER-ID"; // 自定义Header键名

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String userId = exchange.getRequest().getHeaders().getFirst(USER_ID_HEADER);
        return chain.filter(exchange)
                .contextWrite(context -> context.put("CURRENT_USER_ID", userId));
    }
}

3. 实现ReactiveAuditorAware接口

Spring Data审计依赖此接口获取当前操作人ID,这里从Reactor Context中读取之前存入的用户ID:

@Component
public class ReactiveUserIdAuditorAware implements ReactiveAuditorAware<String> {
    private static final String CONTEXT_KEY = "CURRENT_USER_ID"; // 和过滤器中键名保持一致

    @Override
    public Mono<String> getCurrentAuditor() {
        return Mono.deferContextual(contextView -> {
            String userId = contextView.getOrDefault(CONTEXT_KEY, null);
            return Mono.justOrEmpty(userId); // 无用户ID时返回空,可根据业务调整为默认值或异常
        });
    }
}

4. 启用Reactive审计功能

根据你使用的数据库添加对应启用注解,例如MongoDB用@EnableReactiveMongoAuditing,JPA用@EnableReactiveJpaAuditing:

@SpringBootApplication
@EnableReactiveMongoAuditing(auditorAwareRef = "reactiveUserIdAuditorAware")
public class AuditDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(AuditDemoApplication.class, args);
    }
}

5. 实体类添加审计注解

在需要审计的实体类字段上标注Spring Data审计注解:

@Document
public class AuditEntity {
    @Id
    private String id;
    private String content;

    @CreatedBy
    private String createdBy; // 创建人ID
    @LastModifiedBy
    private String lastModifiedBy; // 最后修改人ID
    @CreatedDate
    private Instant createdDate; // 创建时间
    @LastModifiedDate
    private Instant lastModifiedDate; // 最后修改时间

    // getter、setter省略
}

注意事项

  • 请求需携带定义好的Header(如X-USER-ID),值为明文用户ID
  • 若需处理用户ID为空的场景,可在过滤器或ReactiveUserIdAuditorAware中添加默认值逻辑或异常抛出逻辑

内容的提问来源于stack exchange,提问作者Anton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:55:42