Secure Spring -Webscoket using Spring -free and access principle from websocket message

Spring Security is a very good framework widely used for authentication and authorization.

I have a requirement in which an application must be authenticated using j_spring_security_check, and only authorized users can request a websocket handler.

I configured spring security at http://malalanayake.wordpress.com/2014/06/27/spring-security-on-rest-api/

And I configured websocket by http://syntx.io/using-websockets-in-java-using-spring-4/ .

I want the main MyPrincipal object to come from the handleTextMessage handler, as shown below:

    @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);
    }

.

+1
2

HttpSessionHandshakeInterceptor websocket spring SpringSecurityContext WebsocketSession

EDIT: 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

, WebSocket Spring Security . (401, .)

3.2.7 4.0.2.RELEASE

:

  • session.getPrincipal() < -
  • SecurityContextHolder.getContext().getAuthentication() < - null

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

Source: https://habr.com/ru/post/1664667/


All Articles