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();
    }
}
相关推荐
还算善良_10 分钟前
【设计模式】单例模式
java·单例模式·设计模式
终末圆16 分钟前
MyBatis—Plus 快速上手【后端 22】
java·开发语言·数据库·后端·sql·spring·mybatis
深情废杨杨18 分钟前
后端Java-SpringBoot整合MyBatisPlus步骤(超详细)
java·spring boot·spring
码代码的小农23 分钟前
SpringBoot自定义异常
java·spring boot·后端
岁岁岁平安26 分钟前
springboot实战学习(10)(ThreadLoacl优化获取用户详细信息接口)(重写拦截器afterCompletion()方法)
java·spring boot·后端·学习·threadlocal·jwt令牌
fareast_mzh30 分钟前
eMule allows you to optimize your queue and sharing efficiency
java·开发语言·数据库
聆听HJ1 小时前
java 解析excel (本地资源)
java·开发语言·excel
不拱地的猪1 小时前
想知道为什么有DICOM格式,YAML格式,XML格式,JSON格式吗?
xml·java·c++·opencv·json
Jason-河山1 小时前
Java中的HTTP请求:使用Apache HttpClient
java·http·apache
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS微服务在线教育系统(JAVA毕业设计)
java·vue.js·spring boot·spring cloud·微服务·开源