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();
    }
}
相关推荐
电商API&Tina8 分钟前
1688 拍立淘接口(item_search_img)测试与接入实战心得
java·大数据·前端·物联网·oracle·json
行走的搬运工14 分钟前
Spring Security_05
java·spring·mybatis
我登哥MVP16 分钟前
【Spring6笔记】 - 11 - JDBCTemplate
java·数据库·spring boot·mysql·spring
也许明天y27 分钟前
Spring AI 核心原理解析:基于 1.1.4 版本拆解底层架构
java·后端·spring
小红的布丁37 分钟前
BIO、NIO、AIO 与 IO 多路复用:select、poll、epoll 详解
java·数据库·nio
lifallen39 分钟前
Flink Checkpoint 流程、Barrier 流动与 RocksDB 排障
java·大数据·flink
疯狂打码的少年43 分钟前
【Day12 Java转Python】Python工程的“骨架”——模块、包与__name__
java·开发语言·python
希望永不加班1 小时前
SpringBoot 自定义 Starter:从零开发一个私有 Starter
java·spring boot·后端·spring·mybatis
悟空码字1 小时前
别再System.out了!这份SpringBoot日志优雅指南,让你告别日志混乱
java·spring boot·后端
一 乐1 小时前
工会管理|基于springboot + vue工会管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·工会管理系统