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();
    }
}
相关推荐
a程序小傲2 分钟前
小红书Java面试被问:java创建对象有哪些方式?
java·开发语言·面试
代码or搬砖11 分钟前
Spring Cache讲解
java·后端·spring
wxin_VXbishe25 分钟前
springboot居家养老管理系统-计算机毕业设计源码55953
java·c++·spring boot·python·spring·django·php
互亿无线明明28 分钟前
国际金融短信:如何为跨境金融业务构建稳定安全的消息通知链路?
java·python·安全·eclipse·django·virtualenv·pygame
Json_28 分钟前
springboot框架 线程池使用与配置,简单粗暴直接用,再也不用自己创建线程了~
java·spring boot·后端
_半夏曲33 分钟前
maven多依赖,由于包路径一样,导致引入类错乱
java·maven
前端小张同学38 分钟前
餐饮小程序需要你们
java·前端·后端
二十雨辰42 分钟前
[SSM]Spring快速入门
java·spring
豆约翰1 小时前
Z字形扫描ccf
java·开发语言·算法
闲人编程1 小时前
权限系统设计与RBAC实现
java·网络·数据库·rbac·权限·codecapsule