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();
    }
}
相关推荐
飞梦工作室3 分钟前
企业级 Spring Boot 邮件系统开发指南:从基础到高可用架构设计
java·spring boot·后端
haiyu柠檬6 分钟前
在Spring Boot中实现Azure的SSO+VUE3前端配置
java·spring boot·后端
百***812742 分钟前
【SpringBoot】SpringBoot中分页插件(PageHelper)的使用
java·spring boot·后端
百***864643 分钟前
SpringBoot中自定义Starter
java·spring boot·后端
q***071443 分钟前
VScode 开发 Springboot 程序
java·spring boot·后端
q***465244 分钟前
Spring中使用Async进行异步功能开发实战-以大文件上传为例
java·后端·spring
q***38511 小时前
SpringCloud实战【九】 SpringCloud服务间调用
java·spring boot·spring cloud
万物皆字节1 小时前
spring ai 初始化工具,代码链分析
spring
岚天start1 小时前
K8S环境中Containerd运行时占用文件定位清理
java·rpc·kubernetes
2501_916766541 小时前
解决idea依赖导入不成功的问题
java·intellij-idea