在 Websocket 会话中访问 UserDetails 对象 Spring MVC

use*_*072 5 spring-mvc spring-security websocket spring-websocket

在 Spring MVC 4 应用程序中通过 websocket 连接发送的调用中,我可以java.security.Principal在将其添加为方法中的参数时获取一个对象。

但是,这基本上只有用户名,我需要UserDetails在登录期间创建的(扩展)对象。

SecurityContextHolder.getContext().getAuthentication()返回null。据我了解,因为 spring 创建了一个特殊的会话来处理 websocket 连接。

问题:有没有办法从 websocket 会话/线程内部访问安全上下文?

(能够访问会话 bean 就足够了)。

ash*_*ley 2

@AuthenticationPrincipal专门用于 REST/MVC 方法。

java.security.Principle但是,通过向带注释的方法添加 Type 参数@MessageMapping,然后从中获取真实UserDetails对象,您可以非常接近,如下所示:

FooUserDetails currentUser = (FooUserDetails) ((Authentication) user).getPrincipal();
Run Code Online (Sandbox Code Playgroud)

这对我来说适用于 Spring Boot 1.5.4