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();
    }
}
相关推荐
小马爱打代码1 天前
Spring Boot:模块化实战 - 保持清晰架构
java·spring boot·架构
小坏讲微服务1 天前
SpringBoot4.0整合knife4j 在线文档完整使用
java·spring cloud·在线文档·knife4j·文档·接口文档·swagger-ui
8***Z891 天前
springboot 异步操作
java·spring boot·mybatis
i***13241 天前
Spring BOOT 启动参数
java·spring boot·后端
坚持不懈的大白1 天前
后端:SpringMVC
java
IT_Octopus1 天前
(旧)Spring Securit 实现JWT token认证(多平台登录&部分鉴权)
java·后端·spring
kk哥88991 天前
Spring详解
java·后端·spring
S***26751 天前
Spring Cloud Gateway 整合Spring Security
java·后端·spring
Tao____1 天前
开源物联网平台
java·物联网·mqtt·开源·设备对接
遇到困难睡大觉哈哈1 天前
Harmony os——ArkTS 语言笔记(四):类、对象、接口和抽象类
java·笔记·spring·harmonyos·鸿蒙