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();
    }
}
相关推荐
嘟嘟w1 小时前
Spring 核心注解深度分析
java·后端·spring
程序员小单1 小时前
WebSocket 与 Spring Boot 整合实践
spring boot·websocket·网络协议
9***Y481 小时前
Java开发工具IntelliJ IDEA技巧
java·开发语言·intellij-idea
Java爱好狂.1 小时前
2025全年Java面试真题总结!
java·jvm·高并发·多线程·java面试·后端开发·java八股文
Charles_go2 小时前
C#中级39、什么是依赖注入设计模式
java·设计模式·c#
ComplexPy2 小时前
ZKMall-B2B2C Redission延时队列
java·redis
q***96582 小时前
深入解析Spring Boot中的@ConfigurationProperties注解
java·spring boot·后端
java1234_小锋2 小时前
讲讲Mybatis的一级、二级缓存?
java·开发语言·mybatis
e***87702 小时前
记录 idea 启动 tomcat 控制台输出乱码问题解决
java·tomcat·intellij-idea
发现你走远了2 小时前
2025 idea 指定配置环境运行springboot 设置active和env启动端口,多端口启动 (保姆级图文)
java·spring boot·intellij-idea