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

Spring如何获取登录用户接口返回的字符串结果并赋值给createdBy变量

解决方案

方式1:直接在POST接口注入Authentication参数

Spring Security支持在任意受认证保护的Controller接口参数中直接注入Authentication对象,无需额外调用你编写的/user接口,直接取值即可:

@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO, Authentication authentication) {
    requestDTO.setCreatedBy(authentication.getName());
    return requestUseCase.createRequest(requestDTO);
}

方式2:封装工具类全局复用(推荐多场景使用)

如果项目中多处需要获取当前登录用户名,可以封装静态工具类从Spring Security上下文直接取值,避免每个接口都重复注入Authentication参数:

  1. 首先编写工具类:
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtils {
    public static String getCurrentUsername() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !auth.isAuthenticated()) {
            // 可根据业务需求调整为返回默认值或抛自定义业务异常
            throw new RuntimeException("当前请求无登录用户信息");
        }
        return auth.getName();
    }
}
  1. 业务接口直接调用工具类:
@PostMapping("/request")
public RequestDTO saveRequest(@RequestBody final RequestDTO requestDTO) {
    requestDTO.setCreatedBy(SecurityUtils.getCurrentUsername());
    return requestUseCase.createRequest(requestDTO);
}

注意事项

  • 两种方式均不需要主动调用/user接口,同一个登录请求的认证信息会被Spring Security存储在当前线程的上下文里,直接取值即可,避免多余的内部HTTP调用损耗
  • 普通同步接口无需额外配置即可直接使用,异步场景下使用需要额外配置SecurityContext的线程传播策略

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:54:05