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();
    }
}
相关推荐
q***78781 天前
Spring Boot的项目结构
java·spring boot·后端
百***17071 天前
Spring Boot spring.factories文件详细说明
spring boot·后端·spring
q***96581 天前
Spring Data JDBC 详解
java·数据库·spring
Kuo-Teng1 天前
LeetCode 118: Pascal‘s Triangle
java·算法·leetcode·职场和发展·动态规划
倚肆1 天前
HttpServletResponse 与 ResponseEntity 详解
java·后端·spring
悟能不能悟1 天前
java List怎么转换为Vector
java·windows·list
yaoxin5211231 天前
241. Java 集合 - 使用 Collections 工厂类处理集合
java·windows
依_旧1 天前
【玩转全栈】----Django基本配置和介绍
java·后端
white-persist1 天前
差异功能定位解析:C语言与C++(区别在哪里?)
java·c语言·开发语言·网络·c++·安全·信息可视化
kokunka1 天前
C#类修饰符功能与范围详解
java·开发语言·c#