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();
    }
}
相关推荐
H H.9 分钟前
Java企业级开发:从框架到工程化实战
java·开发语言·经验分享·其他·课程设计
wno7049 分钟前
springboot整合FastDFS
java·spring boot·后端
顧棟1 小时前
组件生命周期设计:从硬编码初始化到状态机
java·ide
特立独行的猫A9 小时前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
一起_java9 小时前
技术文章-基于Dify-Agent的智能问答系统设计与实现
java·spring boot·后端·agent·dify
Flynn Liang10 小时前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型
吃我一窝jio11 小时前
Python与Go线程模型深度对比
java·开发语言·python
这个昵称不容易12 小时前
SpringBoot 购物推荐网站的设计与实现:120 个 Java 文件、147 个接口、13 张表,附真实运行截图
java·springboot·毕设
文丑颜不良啊12 小时前
LeetCode3041~3060题目解析
java·leetcode
文丑颜不良啊13 小时前
LeetCode3101~3120题目解析
java·leetcode