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();
    }
}
相关推荐
Barkamin1 小时前
队列的实现(Java)
java·开发语言
骇客野人1 小时前
自己手搓磁盘清理工具(JAVA版)
java·开发语言
J2虾虾2 小时前
在SpringBoot中使用Druid
java·spring boot·后端·druid
清风徐来QCQ2 小时前
Java笔试总结一
java·开发语言
10Eugene2 小时前
C++/Qt自制八股文
java·开发语言·c++
程序员小假2 小时前
为什么要有 time _wait 状态,服务端这个状态过多是什么原因?
java·后端
kuntli3 小时前
p命名空间注入原理详解
spring
yuweiade3 小时前
【Spring】Spring MVC案例
java·spring·mvc
罗超驿4 小时前
Java数据结构_链表
java·数据结构·链表
小璐资源网4 小时前
C++中如何正确区分`=`和`==`的使用场景?
java·c++·算法