spring security 无法获取登录用户

起因:springboot 2.7.x 升级到 3.5.x

导致 spring security 升级

导致问题原因在于默认持久化改变了

官方文档

https://docs.spring.io/spring-security/reference/6.5/servlet/authentication/session-management.html#requireexplicitsave

解决方案 二选一

改配置 SecurityFilterChain 中加上

复制代码
.securityContext(securityContext -> securityContext
            .requireExplicitSave(false) // 允许自动保存,避免手动操作
        );

代码中保存

复制代码
	// in login controller
    
    @Autowired
    private SecurityContextRepository securityContextRepository;
   
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest req, 
                                   HttpServletRequest request, 
                                   HttpServletResponse response) {
            //...... do login and get auth

            // 创建并设置 SecurityContext
            SecurityContext context = SecurityContextHolder.createEmptyContext();
            context.setAuthentication(auth);
            SecurityContextHolder.setContext(context);

            // 手动保存到 Repository(如 Session)
            securityContextRepository.saveContext(context, request, response);

            return ResponseEntity.ok("Login success");
    }
相关推荐
努力的小郑13 小时前
SQL 性能避坑:为什么阿里强制禁用 ORDER BY RAND()?
java·mysql·性能优化
悟能不能悟13 小时前
前端调用a服务,a服务将请求用controller+openfeign调用b服务,接口参数中有header参数和body,a服务应该怎么设置,才简单
java·开发语言·前端
2501_9418859613 小时前
从接口演化到系统自治的互联网工程语法重构与多语言实践思路拆解分享文
java·开发语言
源代码•宸13 小时前
goframe框架签到系统项目开发(补签逻辑实现、编写Lua脚本实现断签提醒功能、简历示例)
数据库·后端·中间件·go·lua·跨域·refreshtoken
武子康13 小时前
大数据-205 线性回归的机器学习视角:矩阵表示、SSE损失与最小二乘
大数据·后端·机器学习
唐叔在学习13 小时前
才知道python还可以这样发消息提醒的
后端·python·程序员
程序员爱钓鱼13 小时前
Node.js 编程实战:前后端结合 - 前端静态资源优化
前端·后端·node.js
2501_9418053113 小时前
在阿姆斯特丹智能港口场景中构建集装箱实时调度与高并发物流数据分析平台的工程设计实践经验分享
java·大数据·算法
小许学java13 小时前
网络原理-HTTP/HTTPS
java·网络·http·https
大爱编程♡13 小时前
JAVAEE-Spring Web MVC
前端·spring·java-ee