Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Spring WebSocket and STOMP: authenticate the handshake, authorize messages

Last updated: 1 Oct 20265 min read
tutorial
IntermediateBy AITrove Editorial

Spring STOMP support maps WebSocket frames to message destinations. The initial HTTP handshake can carry the authenticated principal into the WebSocket session, but an open socket is not permission to send to every destination.

Separate application commands from subscriptions

Clients send commands to an application prefix, while a broker prefix routes subscriptions and broadcasts. Restrict who may send, subscribe and receive at the message layer. Spring Security can authorize inbound messages through a channel interceptor. Do not trust a receipt ID typed into a destination as proof of ownership.

Java
package in.aitrove.receipts;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
class ReceiptSocketRoutes implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry endpoints) {
        endpoints.addEndpoint("/ws/receipts");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry broker) {
        broker.setApplicationDestinationPrefixes("/app");
        broker.enableSimpleBroker("/topic");
    }
}

The simple broker is an in-process teaching choice. It is not a durable queue and does not by itself share subscriptions across application replicas. A broker relay or a separate messaging system changes the deployment and failure contract. A browser connection can stay open for minutes or hours, so bound sessions, message size, per-client rate and slow-consumer buffers.

Read the authentication source

For a typical session-backed browser handshake, Spring associates the HTTP principal with the WebSocket session. STOMP CONNECT login and passcode headers are not a substitute for that authentication path by default. Cross-origin handshake policy and CSRF behavior need a browser test; a successful local WebSocket connection says little about a production proxy.

Common Mistakes

  • Publishing private receipt updates to a shared topic.
  • Trusting client-supplied destination names without object-level authorization.
  • Calling the simple broker a durable message store.
  • Forgetting that a long-lived socket consumes memory and connection capacity.

Read next

HTTP security, tenant ownership, and durable delivery limits.

spring
spring-boot
websocket-stomp-boundary
Storage details