spring websocket 调用受权限保护的方法失败

版本

spring-security 5.6.10

spring-websocket 5.3.27

现象

通过AbstractWebSocketHandler实现websocket端点处理器

调用使用@PreAuthorize注解的方法报错,无法在SecurityContext中找到认证信息

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException

An Authentication object was not found in the SecurityContext

原因

调用websockethandler的线程非用户会话线程,所以安全上下文中没有认证信息

解决

在处理消息时将WebsocketSession中保存的认证信息设置到SecurityContext中

java 复制代码
import org.springframework.web.socket.handler.AbstractWebSocketHandler;
public class MyWsHandler extends AbstractWebSocketHandler {
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		// 在安全上下文中设置认证信息
        SecurityContextHolder.getContext().setAuthentication((Authentication)session.getPrincipal());
        super.handleMessage(session, message);
    }
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 调用受保护的方法
        this.service.doSomething();
    }
}
相关推荐
HAPPY酷13 小时前
3A游戏图形设置终极优化指南:从通用法则到实战应用
java·前端·游戏
达达爱吃肉13 小时前
openclaw 4.2 飞书出图的bug
java·前端·数据库
想不明白的过度思考者13 小时前
SpringAOP:Java 三大代理模式:从静态代理到 JDK & CGLIB 动态代理
java·开发语言·代理模式
yaoyouzhong13 小时前
MySQL中DROP、TRUNCATE和DELETE
java
Meepo_haha13 小时前
Spring boot 3.3.1 官方文档 中文
java·数据库·spring boot
__土块__13 小时前
一次 Spring 循环依赖源码走读:从三级缓存误用到 Bean 生命周期深度解析
java·spring·源码分析·aop·bean生命周期·循环依赖·三级缓存
妙蛙种子31113 小时前
【Java设计模式 | 创建者模式】单例模式
java·开发语言·后端·单例模式·设计模式
种时光的人13 小时前
Spring AI 工具调用(ToolCalling)完整使用教程
java·人工智能·后端·spring·ai·java开发·spring ai
立莹Sir15 小时前
Spring Bean 生命周期详解
java·python·spring
uElY ITER16 小时前
Spring全家桶简介
java·后端·spring