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();
    }
}
相关推荐
Assby1 小时前
从洋葱模型看Java与Go的设计哲学:为什么它们如此不同?
java·后端·架构
belhomme2 小时前
(面试题)Netty 线程模型
java·面试·netty
NE_STOP6 小时前
MyBatis-plus进阶之映射与条件构造器
java
玹外之音7 小时前
揭秘 Spring AI 文档切割:从"暴力分割"到"语义智能"的进阶之路
spring·openai·ai编程
Seven979 小时前
NIO的零拷贝如何实现高效数据传输?
java
架构师沉默1 天前
别又牛逼了!AI 写 Java 代码真的行吗?
java·后端·架构
Java水解1 天前
微服务架构下Spring Session与Redis分布式会话实战全解析
后端·spring
数据智能老司机1 天前
如何对 AI Web 智能体进行身份认证
websocket·agent
后端AI实验室1 天前
我把一个生产Bug的排查过程,交给AI处理——20分钟后我关掉了它
java·ai
凉年技术1 天前
Java 实现企业微信扫码登录
java·企业微信