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();
    }
}
相关推荐
Seven972 小时前
Condition底层机制剖析:多线程等待与通知机制
java
怒放吧德德11 小时前
Spring Boot 实战:RSA+AES 接口全链路加解密(防篡改 / 防重放)
java·spring boot·后端
郑州光合科技余经理15 小时前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
大大水瓶16 小时前
Tomcat
java·tomcat
dustcell.16 小时前
haproxy七层代理
java·开发语言·前端
游离态指针16 小时前
以为发消息=下单成功?RabbitMQ从0到秒杀实战的完整踩坑笔记
java
BD_Marathon16 小时前
工厂方法模式
android·java·工厂方法模式
玹外之音16 小时前
Spring AI MCP 无状态服务器实战:构建AI智能用户管理系统
java·后端
what丶k16 小时前
Spring AI 多模态开发全解析:从入门到企业级落地
后端·spring·ai编程
java干货16 小时前
Redis 的 ZipList 是什么?它是怎么解决内存碎片问题的?
java