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();
    }
}
相关推荐
彦楠8 小时前
指定Tomcat运行的JDK地址
java·开发语言·tomcat
Byron__8 小时前
JVM垃圾回收与调优核心面试笔记(引用计数/GC算法/CMS/G1/参数调优)
java·jvm·笔记·面试
XiYang-DING8 小时前
【Spring】 SpringBoot 配置文件
java·spring boot·spring
那小子、真烦8 小时前
Hermes Agent Chat 方法分析
java·开发语言
01_ice8 小时前
Java抽象类和接口
java·开发语言
小马爱打代码8 小时前
Spring源码 第七篇:Spring Boot 自动配置原理深度拆解
java·spring boot·spring
日取其半万世不竭8 小时前
给 Docker 容器设置 CPU 和内存限制,避免单个服务拖垮整机
java·docker·容器
铁皮哥8 小时前
【agent 开发】Claude Code 的 Skill 是怎么被加载的?从 name/description 到 SKILL.md 再到资源文件
java·服务器·数据库·python·gitee·github·软件工程
白宇横流学长9 小时前
基于SpringBoot实现的校园失物招领平台设计与实现【源码+文档】
java·spring boot·后端
罗超驿9 小时前
6.Java多线程详解:Thread类、线程属性与start()方法深度解析
java·开发语言·面试·java-ee