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

时间:2014-09-03 09:31:27

标签: java spring spring-security websocket

Spring Security是一个非常好的框架,广泛用于Authentication&授权。

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

我已根据http://malalanayake.wordpress.com/2014/06/27/spring-security-on-rest-api/

配置了spring security

我已根据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);
    }

请尽快重播。

2 个答案:

答案 0 :(得分:2)

在websocket配置中添加HttpSessionHandshakeInterceptor允许将spring安全主体对象从SpringSecurityContext传递到WebsocketSession

编辑: 的 HandshakeInterceptor.java

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor{

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Map<String, Object> 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

<bean id="websocket" class="co.syntx.example.websocket.handler.WebsocketEndPoint"/>

<websocket:handlers>
    <websocket:mapping path="/websocket" handler="websocket"/>
    <websocket:handshake-interceptors>
    <bean class="co.syntx.example.websocket.HandshakeInterceptor"/>
    </websocket:handshake-interceptors>
</websocket:handlers>

答案 1 :(得分:1)

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

Testet 3.2.7和4.0.2.RELEASE

两个版本都有:

  • session.getPrincipal()&lt; - 此处的值
  • SecurityContextHolder.getContext().getAuthentication()&lt; - null here

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