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();
    }
}
相关推荐
孟陬1 小时前
国外技术周刊 #1:Paul Graham 重新分享最受欢迎的文章《创作者的品味》、本周被划线最多 YouTube《如何在 19 分钟内学会 AI》、为何我不
java·前端·后端
想用offer打牌1 小时前
一站式了解四种限流算法
java·后端·go
华仔啊2 小时前
Java 开发千万别给布尔变量加 is 前缀!很容易背锅
java
也些宝3 小时前
Java单例模式:饿汉、懒汉、DCL三种实现及最佳实践
java
Nyarlathotep01133 小时前
SpringBoot Starter的用法以及原理
java·spring boot
wuwen53 小时前
WebFlux + Lettuce Reactive 中 SkyWalking 链路上下文丢失的修复实践
java
SimonKing4 小时前
GitHub 10万星的OpenCode,正在悄悄改变我们的工作流
java·后端·程序员
Seven974 小时前
虚拟线程深度解析:轻量并发编程的未来趋势
java
雨中飘荡的记忆14 小时前
ElasticJob分布式调度从入门到实战
java·后端