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();
    }
}
相关推荐
色空大师9 分钟前
【Result<T>泛型接收转化失败】
java·泛型
Geoking.14 分钟前
【设计模式】中介者模式(Mediator)详解
java·设计模式·中介者模式
大猫和小黄15 分钟前
Java异常处理:从基础到SpringBoot实战解析
java·开发语言·spring boot·异常
hero.fei34 分钟前
kaptcha 验证码生成工具在springboot中集成
java·spring boot·后端
mikelv0135 分钟前
实现返回树状结构小记
java·数据结构
Duang007_35 分钟前
【LeetCodeHot100 超详细Agent启发版本】两数之和 (Two Sum)
java·人工智能·python
色空大师42 分钟前
maven引入其他项目依赖爆红
java·maven
yangminlei1 小时前
深入理解Sentinel:分布式系统的流量守卫者
java
JavaEdge.1 小时前
java.io.IOException: Previous writer likely failed to write hdfs报错解决方案
java·开发语言·hdfs
J_liaty1 小时前
基于ip2region.xdb数据库从IP获取到属地解析全攻略
java·网络·后端