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();
    }
}
相关推荐
noBt1 天前
Windows IDEA 卡顿严重
java·ide·intellij-idea
h7ml1 天前
淘宝返利软件的跨端同步架构:Java RESTful API+GraphQL满足Web/APP/小程序的多端数据需求
java·架构·restful
shuair1 天前
redis缓存预热、缓存击穿、缓存穿透、缓存雪崩
redis·spring·缓存
qq_336313931 天前
javaweb-web基础(springboot入门)
java·开发语言·mysql
闻哥1 天前
从测试坏味道到优雅实践:打造高质量单元测试
java·面试·单元测试·log4j·springboot
smileNicky1 天前
统一网关的登录流程总结
java
计算机程序设计小李同学1 天前
基于 Spring Boot + Vue 的龙虾专营店管理系统的设计与实现
java·spring boot·后端·spring·vue
LiZhen7981 天前
SpringBoot 实现动态切换数据源
java·spring boot·mybatis
周航宇JoeZhou1 天前
JB2-7-HTML
java·前端·容器·html·h5·标签·表单
JZC_xiaozhong1 天前
多系统权限标准不统一?企业如何实现跨平台统一权限管控
java·大数据·微服务·数据集成与应用集成·iam系统·权限治理·统一权限管理