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();
    }
}
相关推荐
utf8mb4安全女神4 小时前
【rsyslog服务】把所有服务的“临界点”以上的错误都保存在/var/log/alert.log⽇志中
java·前端·javascript
带刺的坐椅4 小时前
Solon Server 启动模式深度解析:从 0.3MB 内核到 10+ Server 插件
java·http·solon·jetty·undertow
郝学胜-神的一滴4 小时前
干货版《算法导论》07:递归视角下的选择排序与归并排序
java·数据结构·c++·python·程序人生·算法·排序算法
掉鱼的猫4 小时前
Solon Server 启动模式深度解析:从 0.3MB 内核到 10+ Server 插件
java·http
shehuiyuelaiyuehao4 小时前
多线程入门
java·python·算法
星夜夏空994 小时前
FreeRTOS学习(7)——任务列表
java·前端·学习
han_hanker4 小时前
BeanUtils.copyProperties 和序列化的问题
java·开发语言·spring boot
野生技术架构师5 小时前
牛客网2026互联网大厂Java面试题汇总,附官方级答案解析
java·开发语言
AZaLEan__5 小时前
多源 BFS
java·开发语言·算法
程序员卷卷狗5 小时前
Java转Go面试速记:Go基础22问,一篇理清高频易错点一篇理清高频易错点
java·面试·golang