Search code examples
javaspring-bootspring-websocket

Spring WebSocket StompHeaderAccessor


If i execute following code, sha.getLogin() and sha.getPasscode() outputs null !? What is wrong with the code?

Client:

var socket = new SockJS('/ws');
stompClient = Stomp.over(socket);
stompClient.connect("123","456", function (frame) {
    //...
});

Server:

@EventListener
private void onSessionConnect(SessionConnectedEvent event)
{
    StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());

    System.out.println(sha.getLogin());
    System.out.println(sha.getPasscode());
}

But if execute following command, the login and passcode is contained.

sha.getMessageHeaders().toString()

Output (no json):

{  
    simpMessageType=CONNECT_ACK,
    simpConnectMessage=GenericMessage[  
        payload=byte[0],
        headers={  
            simpMessageType=CONNECT,
            stompCommand=CONNECT,
            nativeHeaders={  
                login=[123],//<<<Login
                passcode=[PROTECTED],//<<<Passcode
                accept-version=[  
                    1.1,
                    1.0
                ],
                heart-beat=[  
                    10000,
                    10000
                ]
            },
            simpSessionAttributes={},
            simpHeartbeat=[J@4b5cea63,
            stompCredentials=[PROTECTED],
            simpSessionId=xhojby2n
        }
    ],
    simpSessionId=xhojby2n
}

Solution

  • You can use accessor.getPasscode() method instead of accessor.getFirstNativeHeader(PASSWORD_HEADER) bacause default StompDecoder protect passcode when setting

    public void setPasscode(@Nullable String passcode) {
        setNativeHeader(STOMP_PASSCODE_HEADER, passcode);
        protectPasscode();
    }
    
    private void protectPasscode() {
        String value = getFirstNativeHeader(STOMP_PASSCODE_HEADER);
        if (value != null && !"PROTECTED".equals(value)) {
            setHeader(CREDENTIALS_HEADER, new StompPasscode(value));
            setNativeHeader(STOMP_PASSCODE_HEADER, "PROTECTED");
        }
    }