2
votes

How authenticate a Spring non-web Websocket over STOMP Java client using SockJs?

Session-based Authentication? Token-based Authentication?

The documentation say:

Existing Web applications already use HTTP based authentication. For example

Spring Security can secure the HTTP URLs of the application as usual. Since a WebSocket session begins with an HTTP handshake, that means URLs mapped to STOMP/WebSocket are already automatically protected and require authentication. Moreover the page that opens the WebSocket connection is itself likely protected and so by the time of the actual handshake, the user should have been authenticated.

http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#websocket-stomp-authentication

Actually I connect without autentication and I'm sending messages. My Java server application use Spring framework, but my clients are java clients, not web clients.

1

1 Answers

2
votes

Official doc says:

String url = "ws://127.0.0.1:8080/endpoint";
StompSessionHandler sessionHandler = new MyStompSessionHandler();
stompClient.connect(url, sessionHandler);

but there is other connect method with additional parameter WebSocketHttpHeaders. I used it for basic authorization:

WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
String auth = "user" + ":" + "password";
headers.add("Authorization", "Basic " + new String(Base64.getEncoder().encode(auth.getBytes())));
stompClient.connect(url, headers, new MyStompSessionHandler());