SpringBoot + WebFlux + Spring Security ,SecurityContextHolder.getContext().getAuthentication()获取不到当前用户

发布时间 2023-04-20 21:10:03作者: zolmk

解决方案

直接在Controller接口方法参数中写入org.springframework.security.core.Authentication,如下:

@GetMapping(path = "/test")
    public Mono<Response<?,?>> test(Authentication authentication) {
        return Mono.just(ResponseUtil.success(authentication != null ? authentication.getPrincipal() : null));
    }

通过log得到的结果是Controller执行线程和执行Fliter的线程不是同一个

后续使用

在调用如ReactiveUserDetailsPasswordService.updatePassword()等方法的前,执行SecurityContextHolder.getContext().setAuthentication(authentication);不然会报错。因为这些方法里面也调用了SecurityContextHolder.getContext().getAuthentication()