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();
    }
}
相关推荐
从此以后自律43 分钟前
Java 并发编程完整讲解
java·开发语言
Sylvia33.1 小时前
足球数据接口开发实战:如何用火星数据API盘活赛事应用
java·服务器·开发语言·数据库·python
小小放舟、1 小时前
PaiCLI-Demo:从零实现 ReAct Agent + Tool Call
java·后端·intellij-idea·springboot·agent·react·tool call
熬夜苦读学习1 小时前
基于websocket的多用户五子棋网页游戏
linux·服务器·网络·websocket·网络协议·游戏·五子棋
ch.ju1 小时前
Java程序设计(第3版)第四章——匿名内部类
java·开发语言
C++、Java和Python的菜鸟2 小时前
第2章 前端Web基础(js、vue+Ajax)
java
harmful_sheep2 小时前
idea相关设置
java·ide·intellij-idea
奋发向前wcx2 小时前
y1,y2总复习笔记2 2026.7.15
java·笔记·算法
han_hanker3 小时前
mybatis-plus 常用方法
java·tomcat·mybatis
长不胖的路人甲3 小时前
CAS讲解
java