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();
    }
}
相关推荐
代码雕刻家1 小时前
3.5.Maven-依赖管理-依赖配置&依赖传递
java·maven
!chen1 小时前
MyBatis-plus拓展之字段类型处理器、自动填充和乐观锁
java·tomcat·mybatis
Jin、yz2 小时前
JAVA 八股
java·开发语言
va学弟2 小时前
Java 网络通信编程(6):视频通话
java·服务器·网络·音视频
pjw198809032 小时前
Spring Framework 中文官方文档
java·后端·spring
jgyzl3 小时前
2026.3.11MyBatis-Plus基本使用与思考
java·数据库·mybatis
Full Stack Developme3 小时前
Java 常用通信协议及对应的框架
java·开发语言
( •̀∀•́ )9203 小时前
Spring Boot 启动报错 `BindException: Permission denied`
java·spring boot·后端
杰克尼3 小时前
苍穹外卖--day10
java·数据库·spring boot·mybatis·notepad++
sjmaysee4 小时前
Windows操作系统部署Tomcat详细讲解
java·windows·tomcat