使用来自websocket消息的spring-security和access principal保护Spring-Webscoket

Spring Security是一个非常好的框架,广泛用于身份validation和授权。

我要求使用j_spring_security_check对应用程序进行身份validation,并且只有授权用户才能向websocket处理程序发出请求。

我根据http://malalanayake.wordpress.com/2014/06/27/spring-security-on-rest-api/配置了弹簧安全性

我根据http://syntx.io/using-websockets-in-java-using-spring-4/配置了websocket。

我希望从handleTextMessage处理程序访问MyPrincipal主体对象,如下所示:

@Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { System.out.println("Protocol: "+session.getAcceptedProtocol()); TextMessage returnMessage = new TextMessage(message.getPayload() + " received at server"); System.out.println("myAttrib=" + session.getAttributes().get("myAttrib")); MyPrincipal user = (MyPrincipal) ((Authentication) session .getPrincipal()).getPrincipal(); System.out.println("User: " + user.getUserId()); session.sendMessage(returnMessage); } 

请尽快重播。

在websocket配置中添加HttpSessionHandshakeInterceptor允许将Spring安全主体对象从SpringSecurityContextWebsocketSession

编辑: HandshakeInterceptor.java

 public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{ @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map attributes) throws Exception { System.out.println("Before Handshake"); return super.beforeHandshake(request, response, wsHandler, attributes); } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { System.out.println("After Handshake"); super.afterHandshake(request, response, wsHandler, ex); } } 

websocket.xml

        

确保使用Spring Security保护WebSocket端点并进行登录。 (401如果没有完成。)

Testet的3.2.7和4.0.2.RELEASE

两个版本都有:

  • session.getPrincipal() < - 这里的值
  • SecurityContextHolder.getContext().getAuthentication() < - null here

     @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) protected void configure(HttpSecurity http) throws Exception { http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .and() .httpBasic().and() .authorizeRequests()