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();
    }
}
相关推荐
贾斯汀玛尔斯16 小时前
每天学一个算法--LSM-Tree(Log-Structured Merge Tree)
java·算法·lsm-tree
bitt TRES16 小时前
springboot与springcloud对应版本
java·spring boot·spring cloud
Y0011123617 小时前
JavaWeb-end
java·servlet·web
bzmK1DTbd17 小时前
Git版本控制:Java项目中的分支管理与合并策略
java·开发语言·git
JWASX19 小时前
【RocketMQ 生产者和消费者】- 事务源码分析(1)
java·rocketmq·java-rocketmq
AlunYegeer20 小时前
JAVA,以后端的视角理解前端。在全栈的路上迈出第一步。
java·开发语言·前端
DFT计算杂谈21 小时前
自动化脚本一键绘制三元化合物相图
java·运维·服务器·开发语言·前端·python·自动化
2301_771717211 天前
Spring Boot 自动配置核心注解
java·spring boot·mybatis
小Y._1 天前
面试被问synchronized锁升级,这5个问题答不上来直接挂!
java
姚青&1 天前
测试技术体系
java·python