如何在消息处理Spring Controller方法中获取Authentication对象

时间:2015-10-16 17:19:58

标签: spring spring-security spring-websocket

我有一个处理REST请求的控制器方法以及STOMP / websocket消息。类似的东西:

@RequestMapping(value="/test")
@MessageMapping(value=".test")
@SendTo(value="/topic/testresponse")
public ResponseEntity<?> test(Principal principal)
{
  Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  ...
  return ResponseEntity.ok(principal.getName());
}

当我从REST客户端调用此方法时,Principal和Authentication对象都会正确填充。但是,当我从STOMP / websocket客户端调用此方法时,将填充Principal对象,但Authentication对象为null。

显然,Spring能够以某种方式获取Authentication对象,即使在websocket的情况下也是如此,因为它填充了Principal对象。我怎么能在我的代码中做到这一点?

我想知道这一点的原因是我需要在未作为控制器方法调用的代码中进行自定义授权检查。

我正在使用Spring Boot 1.2.2。

感谢。

0 个答案:

没有答案