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();
    }
}
相关推荐
014-code6 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
java1234_小锋7 小时前
Java高频面试题:Springboot的自动配置原理?
java·spring boot·面试
末央&8 小时前
【天机论坛】项目环境搭建和数据库设计
java·数据库
xiaoye37088 小时前
Spring 中高级面试题
spring·面试
枫叶落雨2228 小时前
ShardingSphere 介绍
java
花花鱼8 小时前
Spring Security 与 Spring MVC
java·spring·mvc
言慢行善9 小时前
sqlserver模糊查询问题
java·数据库·sqlserver
专吃海绵宝宝菠萝屋的派大星9 小时前
使用Dify对接自己开发的mcp
java·服务器·前端
大数据新鸟9 小时前
操作系统之虚拟内存
java·服务器·网络
Tong Z9 小时前
常见的限流算法和实现原理
java·开发语言