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();
    }
}
相关推荐
code2cat2 分钟前
Java进阶篇之LongAdder:把统计更新分散,再读取总和
java·并发编程·原子类·longadder
凯哥Java12 分钟前
写代码怎么避免逻辑漏洞?
java·开发语言·人工智能·自动化
Ivanqhz30 分钟前
正余弦位置编码(Sinusoidal Positional Encoding)
java·linux·数据库
BD_Marathon44 分钟前
消息对象中字段的说明
java·前端·python
zlpzlpzyd1 小时前
nacos的openapi地址
java
落魄实习生2 小时前
Agent Scope Java 2.x 系列【10】Middleware
java·开发语言·ai
ZealSinger3 小时前
Spring7 RestTemplate弃用迁移
java·spring·后端开发·restclient
朝朝辞暮i3 小时前
C++ 第 13 课:值传递 —— 为什么函数里改了,外面却没变?
java·c++·算法
弹简特3 小时前
【Java项目-企悦抽】16-抽奖模块01-获取活动完整信息接口实现
java·开发语言·状态模式·springboot
萧瑟余晖3 小时前
Spring 资源与环境配置体系详解
spring