首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >spring websocket 调用受权限保护的方法失败

spring websocket 调用受权限保护的方法失败

作者头像
路过君
发布2023-08-02 09:29:01
发布2023-08-02 09:29:01
7830
举报

版本

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中

代码语言:javascript
复制
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();
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-07-31,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 版本
  • 现象
  • 原因
  • 解决
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档