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();
    }
}
相关推荐
小南家的青蛙25 分钟前
LeetCode面试题 01.09 字符串轮转
java·leetcode
秋野酱40 分钟前
基于javaweb的SpringBoot爱游旅行平台设计和实现(源码+文档+部署讲解)
java·spring boot·后端
饕餮争锋1 小时前
org.slf4j.MDC介绍-笔记
java·开发语言·笔记
shane-u1 小时前
Maven私服搭建与登录全攻略
java·maven
半部论语1 小时前
jdk多版本切换,通过 maven 指定编译jdk版本不生效,解决思路
java·开发语言·maven·intellij-idea
有梦想的攻城狮1 小时前
spring中的@Async注解详解
java·后端·spring·异步·async注解
Python ml1 小时前
Tomcat与纯 Java Socket 实现远程通信的区别
java·开发语言·tomcat
qq_12498707531 小时前
原生小程序+springboot+vue医院医患纠纷管理系统的设计与开发(程序+论文+讲解+安装+售后)
java·数据库·spring boot·后端·小程序·毕业设计
伊成2 小时前
一文详解Spring Boot如何配置日志
java·spring boot·单元测试
lybugproducer2 小时前
浅谈 Redis 数据类型
java·数据库·redis·后端·链表·缓存